require 'csv'
module CsvParser
  module ClassMethods
    # just returns an array of hashes of the raw data
    def parse(filename, delimiter, order_of_items = {})
      raise "Please provide a hash of person attributes with the position in the CSV as their values" unless order_of_items
      # really wish I could use ActiveSupport's returning here :)
      ret_val = []
      parse_csv(filename, delimiter) do |row|
        # we populate the results hash with :first_name => "Bob" if you pass in :first_name => 3 (csv row)
        hashed_row = {}
        order_of_items.each do |k,v|
          hashed_row[k] = row[v].strip
        end
        ret_val << hashed_row
      end
      ret_val
    end

    private
    def parse_csv(filename, delimiter = ",")
      csv_contents = CSV.read(filename, :col_sep => delimiter)
      csv_contents.each do |row|
        yield(row)
      end
    end
  end

  def self.included(base)
    base.extend(ClassMethods)
  end
end