class DataKit::CSV::Converter

Attributes

analysis[RW]
csv[RW]
output_path[RW]

Public Class Methods

convert(csv, analysis, output_path) click to toggle source
# File lib/data_kit/csv/converter.rb, line 37
def convert(csv, analysis, output_path)
  converter = new(csv, analysis, output_path)
  converter.execute
  converter
end
new(csv, analysis, output_path) click to toggle source
# File lib/data_kit/csv/converter.rb, line 11
def initialize(csv, analysis, output_path)
  @csv = csv
  @analysis = analysis
  @output_path = File.expand_path(output_path)
end

Public Instance Methods

execute() click to toggle source
# File lib/data_kit/csv/converter.rb, line 17
def execute
  ::CSV.open(output_path, 'wb') do |writer|
    first = true
    converted = []
    csv.each_row do |row|
      if first
        first = false
        writer << csv.headers
      end
      
      writer << convert_row(csv.headers, row)
    end
  end
end
field_types() click to toggle source
# File lib/data_kit/csv/converter.rb, line 32
def field_types
  @field_types ||= analysis.field_types
end

Private Instance Methods

convert_row(headers, row) click to toggle source
# File lib/data_kit/csv/converter.rb, line 46
def convert_row(headers, row)
  converted = []
  headers.each_with_index do |field_name, index|
    converted << convert_value(row[index], field_types[field_name])
  end
  converted
end
convert_value(value, type) click to toggle source
# File lib/data_kit/csv/converter.rb, line 54
def convert_value(value, type)
  if value.nil? || type == :string || type == :empty
    return value.to_s
  else
    formatted = Converters::Number.reformat(value)

    case type
    when :integer
      return Converters::Integer.convert(formatted)
    when :number
      return Converters::Number.convert(formatted)
    when :boolean
      return Converters::Boolean.convert(value)
    when :datetime
      return Converters::DateTime.convert(value).strftime("%Y-%m-%dT%H:%M:%SZ")
    end
  end
end