class CSVParser
Public Class Methods
new(csv)
click to toggle source
# File lib/csv_parser.rb, line 25 def initialize(csv) @csv = csv end
parsers()
click to toggle source
# File lib/csv_parser.rb, line 3 def parsers @parsers ||= [] end
Private Class Methods
parse(criteria, params={}, &block)
click to toggle source
Add a column parser
# File lib/csv_parser.rb, line 10 def parse(criteria, params={}, &block) parsers << { criteria: criteria, block: block, }.merge(params) end
parse_once(criteria, params={}, &block)
click to toggle source
Add a parser that will only get called once per row
# File lib/csv_parser.rb, line 18 def parse_once(criteria, params={}, &block) parse criteria, { once: true, }.merge(params), &block end
Public Instance Methods
each() { |parse_row row| ... }
click to toggle source
# File lib/csv_parser.rb, line 31 def each # Get header values used later in prasing @headers = @csv.shift.map(&:to_s).map(&:strip) # Parse each row @csv.each do |row| yield parse_row row end end
Protected Instance Methods
[](name)
click to toggle source
# File lib/csv_parser.rb, line 95 def [](name) @attributes[name] end
[]=(name, val)
click to toggle source
# File lib/csv_parser.rb, line 99 def []=(name, val) @attributes[name] = val end
Private Instance Methods
defaults()
click to toggle source
Default hash values to use for each row
# File lib/csv_parser.rb, line 89 def defaults Hash.new end
match?(parser, val, key)
click to toggle source
Does the parser criteria match the column?
# File lib/csv_parser.rb, line 79 def match?(parser, val, key) case criteria = parser[:criteria] when Symbol send criteria, key else criteria === key end end
onced?(parser)
click to toggle source
Is the parser a once parser and has already been executed for this row?
# File lib/csv_parser.rb, line 74 def onced?(parser) parser[:once] && @executed.include?(parser) end
parse_row(row)
click to toggle source
# File lib/csv_parser.rb, line 47 def parse_row(row) # Create a new attributes hash for this row, this will be our result @attributes = defaults # Keep track of which parsers have already been executed for this row @executed = [] # Parse each column of the row row.each_with_index do |val, i| parse_val val.to_s.strip, @headers[i].to_s end # Return the attributes that were built using #[]= @attributes end
parse_val(val, key)
click to toggle source
Parse a column value
# File lib/csv_parser.rb, line 63 def parse_val(val, key) parsers.each do |parser| # Execute any parsers that match this column if ! onced?(parser) && match?(parser, val, key) instance_exec val, key, &parser[:block] @executed << parser end end end
parsers()
click to toggle source
# File lib/csv_parser.rb, line 43 def parsers self.class.parsers end