CSV ORM

  • Thread starter Jon Egil Strand
  • Start date
J

Jon Egil Strand

Greetings

Do we have an object relational mapper for csv files?

#data:
first_name;last_name;phone
peter;pan;12345

#ROW ACCESS
person.first_name => "peter"
person.last_name => "pan"



Even nicer if it header_row and separation_character can be specified?


I've considered csvparser-0.1.1 and FasterCSV, but as far as I can tell

- csvparser is a little thin on header_row/sep_char
- FasterCSV's synax
table[:first_name][1]
this kind'o does the job, but I would prefer the implementation of
the datasource to be a bit less visible in the rest of the app


Thank's for your time

JE
 
J

James Edward Gray II

Greetings

Do we have an object relational mapper for csv files?

#data:
first_name;last_name;phone
peter;pan;12345

#ROW ACCESS
person.first_name => "peter"
person.last_name => "pan"

First idea:

#!/usr/bin/env ruby -w

require "rubygems"
require "faster_csv"

require "ostruct"

# load
people = FCSV( DATA, :col_sep => ";",
:headers => true,
:header_converters => :symbol ) do |csv|
csv.inject(Array.new) { |all, person| all + [OpenStruct.new
(person.to_hash)] }
end

# example usage
puts people.map { |person| person.first_name }

__END__
First Name;Last Name;Phone
Peter;Pan;111-1111
Wendy;Darling;222-2222

Second idea, if you are in control of the CSV data:

#!/usr/bin/env ruby -w

require "rubygems"
require "faster_csv"

require "pp"

Person = Struct.new:)first_name, :last_name, :phone)

people = [ %w[Peter Pan 111-1111],
%w[Wendy Darling 222-2222] ].inject(Array.new) do |all,
attrs|
all + [Person.new(*attrs)]
end

# dump
csv = FCSV.dump(people)
puts csv
puts

# load
reloaded = FCSV.load(csv)
pp reloaded
puts

# use
puts reloaded.map { |person| person.first_name }

Hope one of those helps.

James Edward Gray II
 
G

Gregory Brown

Gregory and James

Thank you so much for your precise and speedy replies, I am thankful both
for your suggestions and for your effort in building these libraries.

With FasterCSV I espescially like the ability to set

:headers => "my;custom;header"

anything in :csv_options gets passed along to FasterCSV in the code I
suggested, so you might be able to see if that'll be helpful somehow.
 

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top