Created
March 17, 2011 21:06
-
-
Save pillowfactory/875130 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
# Given a CSV record format like: | |
# john,doe,blonde,26 | |
CsvMapper.import('blah') do | |
map_to Person | |
first_name # maps to string by default | |
last_name # maps to string by default | |
_SKIP_ # skip the 'hair color' column | |
# but age should be an integer... | |
age.map {|row, index| row[index].to_i} | |
end |
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
# Given | |
class Business | |
attr_accessor :name, :net_worth | |
attr_accessor :address | |
attr_accessor :employees | |
end | |
class Address | |
attr_accessor :line_1, :line_2, :city, :state, :zip | |
end | |
class Employee | |
attr_accessor :first_name, :last_name | |
end | |
# Import with CSV Mapper | |
CsvMapper.map_to(Business).import('path') do |config| | |
config.start_at_row 1 # Skip the first row (probably a header row) | |
config.stop_at_row 10 # Stop parsing on the 10th row | |
name # Parse to String by default | |
net_worth :type => Float # Parse column value Float | |
# Map an aggregate model that is an instance of Address | |
address.map_to Address do | |
line_1 | |
line_2 | |
city | |
state.map {|value| value.to_s.upcase} # Parse the raw value using the given block | |
zip | |
end | |
# Map a collection of employees that are instances of Employee | |
employees.map_to Employee, :count => 2 do | |
first_name | |
last_name | |
end | |
end | |
# Results - An array of two instances of a Business; each with a fully populated Address instance as the value of the address attribute |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment