Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/rtp-connect/ruby_extensions.rb
Overview
Extension to the String class. These facilitate processing and analysis of RTPConnect strings.
Instance Method Summary collapse
-
#checksum ⇒ Fixnum
Determines the checksum (CRC) for a given string.
-
#elements ⇒ Array<String>
Splits the elements of a string separated by comma.
-
#repair_csv ⇒ String
Reformats a string, attempting to fix broken CSV format.
-
#value ⇒ String
Removes leading & trailing double quotes from a string.
-
#values(repair = false) ⇒ Array<String>
Splits the elements of a CSV string (comma separated values) and removes quotation (leading and trailing double-quote characters) from the extracted string elements.
-
#wrap ⇒ String
Wraps double quotes around the string.
Instance Method Details
#checksum ⇒ Fixnum
Determines the checksum (CRC) for a given string.
13 14 15 16 17 18 19 |
# 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 |
#elements ⇒ Array<String>
Splits the elements of a string separated by comma.
25 26 27 |
# File 'lib/rtp-connect/ruby_extensions.rb', line 25 def elements self.split(',') end |
#repair_csv ⇒ String
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.
35 36 37 38 |
# File 'lib/rtp-connect/ruby_extensions.rb', line 35 def repair_csv arr = self[1..-2].split('","') "\"#{arr.collect{|e| e.gsub('"', '')}.join('","')}\"" end |
#value ⇒ String
Removes leading & trailing double quotes from a string.
44 45 46 |
# File 'lib/rtp-connect/ruby_extensions.rb', line 44 def value self.gsub(/\A"|"\Z/, '') end |
#values(repair = false) ⇒ Array<String>
Splits the elements of a CSV string (comma separated values) and removes quotation (leading and trailing double-quote characters) from the extracted string elements.
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# 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 |
#wrap ⇒ String
Wraps double quotes around the string.
77 78 79 |
# File 'lib/rtp-connect/ruby_extensions.rb', line 77 def wrap '"' + self + '"' end |