Created
December 16, 2010 17:02
-
-
Save samnang/743655 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name, points, country, likes | |
'sarah', 200, 'USA', 'dog' | |
'ashbb', 140, 'Japan', 'cat' | |
'satish', 203, 'India', 'tiger' | |
'vic', 1500, 'USA', 'elephant' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment