Sha256: d5b562611cd0867b88008052534c6d976ffb74aa1890231f1cedc2cdf9028510

Contents?: true

Size: 1.02 KB

Versions: 1

Compression:

Stored size: 1.02 KB

Contents

module DataImporter
  class CsvReader
    attr_accessor :csv, :headers, :seprator, :mappings

    def initialize(file_name, mappings=nil)
      @seprator = ","
      file = File.open(file_name, 'r')
      @csv = CSV.new(file, headers: true)
      @headers = File.open(file_name, 'r') {|f| f.readline.chomp}.split(@seprator)
      @mappings = mappings || get_default_mappings
    end

    def row
      @csv.shift
    end

    def get_mapped_row_hash
      csv_row = row
      return nil unless csv_row
      csv_row = csv_row.to_hash
      mappings.each { |mk, mv| csv_row[mv] = csv_row.delete(mk)}
      csv_row
    end

    private
    def get_default_mappings
      @headers.inject({}) {|mh, h| mh[h] = get_field_name(h); mh}
    end

    def get_field_name(field)
      field.downcase.gsub(/\s+/, ' ').gsub(" ","_").to_sym
    end
  end

  class Report
    attr_accessor :successful, :unsuccessful, :total, :time_elapsed

    def initialize
      @successful = 0
      @unsuccessful = 0
      @total = 0
      @time_elapsed = 0
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
data_importer-0.1.0 lib/data_importer/csv_reader.rb