class String
Extension to the String
class. These facilitate processing and analysis of RTPConnect strings.
Public Instance Methods
Determines the checksum (CRC) for a given string.
@return [Fixnum] the checksum (a 16 bit unsigned integer)
# File lib/rtp-connect/ruby_extensions.rb, line 13 def checksum crc = RTP::CRC_SEED self.each_codepoint do |byte| crc = RTP::CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >> 8) end return crc end
Splits the elements of a string separated by comma.
@return [Array<String>] an array of the string values originally separated by a comma
# File lib/rtp-connect/ruby_extensions.rb, line 25 def elements self.split(',') end
Reformats a string, attempting to fix broken CSV format. Note that this method attempts to fix the CSV in a rather primitive, crude way: Any attributes containing a “ character, will have these characters simply removed.
@return [String] the processed string
# File lib/rtp-connect/ruby_extensions.rb, line 35 def repair_csv arr = self[1..-2].split('","') "\"#{arr.collect{|e| e.gsub('"', '')}.join('","')}\"" end
Removes leading & trailing double quotes from a string.
@return [String] the processed string
# File lib/rtp-connect/ruby_extensions.rb, line 44 def value self.gsub(/\A"|"\Z/, '') end
Splits the elements of a CSV string (comma separated values) and removes quotation (leading and trailing double-quote characters) from the extracted string elements.
@param [Boolean] repair if true, the method will attempt to repair a string that fails CSV processing, and then try to process it a second time @return [Array<String>] an array of the comma separated values
# File lib/rtp-connect/ruby_extensions.rb, line 55 def values(repair=false) begin CSV.parse(self).first rescue StandardError => e if repair RTP.logger.warn("CSV processing failed. Will attempt to reformat and reprocess the string record.") begin CSV.parse(self.repair_csv).first rescue StandardError => e RTP.logger.error("Unable to parse the given string record. Probably the CSV format is invalid and beyond repair: #{self}") end else RTP.logger.error("Unable to parse the given string record. Probably invalid CSV format: #{self}") raise e end end end
Wraps double quotes around the string.
@return [String] the string padded with double-quotes
# File lib/rtp-connect/ruby_extensions.rb, line 77 def wrap '"' + self + '"' end