Last active
October 7, 2015 15:38
-
-
Save vicentereig/3188109 to your computer and use it in GitHub Desktop.
Awesome FasterCSV Features. Thanks @JEG2
This file contains 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
# 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",[email protected] | |
2,"Konstantin Krauss",[email protected] | |
3,"Vicente Reig",[email protected] | |
CSV | |
CSV_INPUT = <<-CSV | |
id,name,email | |
1,"Chris Floess",[email protected] | |
2,"Konstantin Krauss",[email protected] | |
3,"Vicente Reig",[email protected] | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
L19 (https://gist.github.com/vicentereig/3188109#file-ruby_csv_simple_object_mapping-rb-L19) change load to parse. load will allow code execution: https://gist.github.com/benmmurphy/4706099