Convertible To CSV plugin

Plugin details

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.

Websitehttp://rubygreenblue.com/project/convertible_to_csv Repositoryhttp://blog.rubygreenblue.com/project/convertible_to_csv Author Keith Rowell Tags csv LicenseMIT

Documentation

Install the plugin:
ruby script/plugin install http://blog.rubygreenblue.com/project/convertible_to_csv

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

Further Documentation

There is currently no advanced documentation for this plugin.

New documentation

Edit plugin | (0 older versions) | Last edited by: hardway, about 1 year ago