RubyGreenBlue

Convertible to csv format options

Posted by keith over 2 years ago

The latest version of convertible to csv can be told how to format particular fields when it returns data for the to_csv method. The default behaviour is to use the to_s method for each field. But sometimes you might want to display the data a little differently.

Use :format_options to specify a format method to be called 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.

Here's an example:

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

As Customer.find(:all).to_csv is invoked, each time the fields "lastname" and "firstname" are output, instead of calling to_s on the fields, calls are made to the format_firstname and format_lastname methods respectively and your csv output will contain upcased firstname and reversed lastname.