class Typedcsv::Headers

Constants

EMPTY_STRING
FALSE
TRUE

Attributes

raw[R]

Public Class Methods

new(raw) click to toggle source
# File lib/typedcsv.rb, line 51
def initialize(raw)
  @raw = raw
end

Public Instance Methods

parse_array(row) click to toggle source
# File lib/typedcsv.rb, line 64
def parse_array(row)
  types.map do |k, type, _, i|
    convert type, row[i]
  end
end
parse_hash(row) click to toggle source
# File lib/typedcsv.rb, line 69
def parse_hash(row)
  types.inject({}) do |memo, (k, type, orig_k, _)|
    v = row.fetch orig_k
    memo[k] = convert(type, v)
    memo
  end
end
types() click to toggle source
# File lib/typedcsv.rb, line 54
def types
  @types ||= raw.each_with_index.map do |raw_k, i|
    k, type = raw_k.split(':', 2)
    if type
      [k, type, "#{k}:#{type}", i]
    else
      [k, 'text', k, i]
    end
  end
end

Private Instance Methods

convert(type, v) click to toggle source
# File lib/typedcsv.rb, line 77
def convert(type, v)
  if v.nil? or v == EMPTY_STRING
    return nil
  end
  case type
  when 'text'
    # defaults to no parsing
    v
  when 'boolean'
    case v
    when TRUE
      true
    when FALSE
      false
    end
  when 'list'
    CSV.parse_line(v)
  when 'date'
    Time.parse(v).to_date
  when 'time'
    Time.parse(v).to_date
  when 'number'
    v.to_f
  else
    v
  end
end