samnang
12/16/2010 - 5:02 PM

customers.txt

ID, account, tel, last_access, name
'A-23-112', 'ashbb', 2234, 'Aug 13th', 'Satoshi'
'B-34-122', 'tiger', 5543, 'May 1st', 'Satish'
'A-15-982', 'pen', 7812, 'Sep 24th', 'Michael'
class Datarecord
  class << self
    def make(file)
      return unless File.exist?(file)

      define_class_with_attributes(file)
    end

    private
    def define_class_with_attributes(file)
      klass_name = file.split(".").first.capitalize
      attributes = open(file).gets.chomp.split(", ").map(&:to_sym)

      klass = Struct.new(*attributes) do
        define_singleton_method(:read) do
          File.open(file) do |f|
            f.readline #ignore header column

            f.readlines.inject([]) do |records, line|
              record = eval("[#{line.chomp}]")
              records << new(*record)
            end
          end
        end
      end

      Object.const_set(klass_name, klass)
    end
  end
end

# ============= Running examples ==================
klass = Datarecord.make 'people.txt'
p klass  #=> People
klass.read.each{|people| p people}

klass = Datarecord.make 'customers.txt'
p klass  #=> Customers
klass.read.each{|people| p people}
name, points, country, likes
'sarah', 200, 'USA', 'dog'
'ashbb', 140, 'Japan', 'cat'
'satish', 203, 'India', 'tiger'
'vic', 1500, 'USA', 'elephant'