CSV Mapper
What
CsvMapper is a small library intended to simplify the common steps involved with importing CSV files to a usable form in Ruby.
Installing
sudo gem install csv-mapper
The basics
CSV Mapper makes it easy to import data from CSV files directly to a collection of any type of Ruby object.
The simplest way to create mappings is declare the names of the attributes in the order corresponding to the CSV file column order. For more complex mappings you can assign lambdas or methods to be used to convert data from the CSV row to the value of the declared attribute.
See CsvMapper RDoc for detailed mapping examples.
Demonstration of usage
Example CSV File Structure
First Name,Last Name,Age John,Doe,27 Jane,Doe,26 Bat,Man,52 ...etc...
Simple Usage Example
require 'csv-mapper' include CsvMapper results = import('/path/to/file.csv') do start_at_row 1 [first_name, last_name, age] end results.first.first_name # John results.first.last_name # Doe results.first.age # 27
Import to ActiveRecord Example
Although CSV Mapper has no dependency on ActiveRecord; it‘s easy to import a CSV file to ActiveRecord models and save them.
require 'csv-mapper' # Define an ActiveRecord model class Person < ActiveRecord::Base; end include CsvMapper results = import('/path/to/file.csv') do map_to Person # Map to the Person ActiveRecord class (defined above) instead of the default OpenStruct. after_row lambda{|row, person| person.save } # Call this lambda and save each record after it's parsed. start_at_row 1 [first_name, last_name, age] end
Forum
http://groups.google.com/group/csv-mapper
How to submit patches
Read the 8 steps for fixing other people’s code and for section 8b: Submit patch to Google Groups, use the Google Group above.
You can fetch the source from:
git clone git://github.com/pillowfactory/csv-mapper.git
Build and test instructions
cd csv-mapper rake test rake install_gem
License
This code is free to use under the terms of the MIT license.
Contact
Comments are welcome. Send an email to Luke Pillow email via the forum
Luke Pillow, 5th December 2008
Theme extended from Paul Battley