public

Awesome FasterCSV Features. Thanks @JEG2

  • Download Gist
ruby_csv_simple_object_mapping.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
# http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#method-c-load
# http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#method-c-dump
# https://github.com/JEG2/faster_csv/blob/master/test/tc_serialization.rb
require 'csv'
 
class Person
attr_accessor :id, :name, :email
 
def self.csv_load(meta, headers, row)
person = Person.new
headers.each.with_index { |h,i|
person.send "#{h}=", row[i]
}
person
end
 
def self.parse(csv)
meta = "class,#{self.to_s}\n"
CSV.parse("#{meta}#{csv}")
end
 
def dump
self.class.dump([self])
end
 
def self.dump(people, io='', options={})
CSV.dump(people, io, options).strip
end
 
def self.csv_meta
[]
end
 
def csv_headers
%w(id name email)
end
 
def csv_dump(headers)
headers.map { |h| self.instance_variable_get "@#{h}" }
end
 
end
 
CSV_DUMP = <<-CSV
class,Person
id=,name=,email=
1,"Chris Floess",chris@propertybase.com
2,"Konstantin Krauss",konstantin@propertybase.com
3,"Vicente Reig",vicente@propertybase.com
CSV
 
CSV_INPUT = <<-CSV
id,name,email
1,"Chris Floess",chris@propertybase.com
2,"Konstantin Krauss",konstantin@propertybase.com
3,"Vicente Reig",vicente@propertybase.com
CSV
 
CSV_DUMP2 = <<-CSV
class,Person
#{CSV_INPUT}
CSV
 
people = Person.parse(CSV_INPUT)
puts people.inspect
dumped = Person.dump(people)
puts dumped
puts "----"
puts Person.parse(dumped).inspect

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.