Class: String

Inherits:
Object
  • Object
show all
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

Instance Method Details

#checksumFixnum

Determines the checksum (CRC) for a given string.

Returns:

  • (Fixnum)

    the checksum (a 16 bit unsigned integer)



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

#elementsArray<String>

Splits the elements of a string separated by comma.

Returns:

  • (Array<String>)

    an array of the string values originally separated by a comma



25
26
27
# File 'lib/rtp-connect/ruby_extensions.rb', line 25

def elements
  self.split(',')
end

#repair_csvString

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.

Returns:

  • (String)

    the processed string



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

#valueString

Removes leading & trailing double quotes from a string.

Returns:

  • (String)

    the processed 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.

Parameters:

  • repair (Boolean) (defaults to: false)

    if true, the method will attempt to repair a string that fails CSV processing, and then try to process it a second time

Returns:

  • (Array<String>)

    an array of the comma separated values



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

#wrapString

Wraps double quotes around the string.

Returns:

  • (String)

    the string padded with double-quotes



77
78
79
# File 'lib/rtp-connect/ruby_extensions.rb', line 77

def wrap
  '"' + self + '"'
end