Sha256: 06b624f5262861c020cacaaf08818d69564de542fb73c178183db3085c8afe08

Contents?: true

Size: 1.27 KB

Versions: 1

Compression:

Stored size: 1.27 KB

Contents

#coding: utf-8
require "csv_to_object/version"
require 'csv'

module CsvToObject
  class CsvToObject

    # Requires the path to the csv file.
    def initialize(input_path)
      @input_path = File.open(input_path)
    end

    # Converts the data lines of the csv file to objects.
    # Objects have the class of the name of the csv file.
    # The first line of the csv file defines the attribute names for the data lines.
    #   person.csv => [person objects]
    #   attribute names are downcased and have spaces replaced with _.
    #   attribute names are strings.
    def to_objects
      objects = []
      file = File.open(@input_path)
      CSV.table(file, {header_converters: header_converter}).each do |row|
        objects << new_object(row.to_hash)
      end
      objects
    end

    private

    def header_converter
      lambda { |h| h.encode(CSV::ConverterEncoding).downcase.gsub(/\s+/, "_") }
    end

    def new_object(attrs)
      @object ? @object.new(attrs) : object_to_create().new(attrs)
    end

    def object_to_create()
      @object = Object::const_get(class_name)
    end
    
    def class_name
      bare_file_name.split('_').map { |word| word.capitalize}.join
    end
    
    def bare_file_name
      File.basename(@input_path).gsub('.csv','')
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
csv_to_object-1.0.4 lib/csv_to_object.rb