Convertible To Csv

Convertible to csv allows you to specify that an ActiveRecord model should respond to a to_csv message. You can also specify if a header row of field names should be used and which fields (and their order) should be used in the csv output.

Licence

Convertible to csv is released under the MIT licence.

Download / Install

The code can be downloaded from the subversion repository: svn://rubygreenblue.com/rubygreenblue_opensource/convertible_to_csv/trunk

  • install as a gem

    sudo gem install convertible_to_csv-x.x.x.gem
    
  • install as a plugin

    script/plugin install svn://rubygreenblue.com/rubygreenblue_opensource/convertible_to_csv/trunk
    

Usage

It is very straight forward to use:

In your model declaration

  • minimal usage:

    class Customer < ActiveRecord::Base
      acts_as_convertible_to_csv
    end
    
  • all possible options:

    class Customer < ActiveRecord::Base
      acts_as_convertible_to_csv :header => true, 
                                 :fields => %w(id firstname lastname email_address),
                                 :format_options => {:lastname => :format_lastname, :firstname => :format_firstname}
      def format_firstname
        firstname.upcase
      end
    
    
      def format_lastname
        lastname.reverse
      end
    end
    

:header, :fields and :format_options are optional.

If :header is omitted, no header row will be used.

If :fields is omitted, the field list returned by human_readable will be used.

Use :format_options to specify some a format method to be run when outputting a field. This is useful, for example, if you have a Time field and you want to format it differently to how Time.to_s displays a time.

Getting the csv data from a collection of records:

Customer.find(:all).to_csv

You can pass a block:

Customer.find(:all).to_csv do |line|
  # do something with each line
end

You can also convert individual records to csv:

Customer.find(:first).to_csv