Navigate/Search

Introducing CSVExportable

This plugin has been replaced by ActsAsCSVExportable, check it out!

I am finally releasing my first Rails Plugin: CSVExportable !

As many great things in the Rails community (and Rails itself) this plugin was born out of necessity. The need of the plugin in my projects defined its functionality and the design decisions taken to make it. Of course the project is open source, and free to modify and redistribute with credits intact.

Current version: 0.9
Download (SVN): Stable 0.9
Follow:
Simple Usage

Here is a very simple usage for exporting all of the items belonging to a certain category.

def index
  @category = Category.find(params[:id])
  @items = @category.items

  responds_to do |wants|
    wants.html
    wants.csv { render :text => @items.to_csv }
  end
end

This will prompt the browser to download the csv file to the users computer. The CSV MimeType and responsiveness to the responds_to method is injected by the plugin. This creates an ‘out-of-the-box’ functionality of csv exporting of any ActiveRecord Model.

You can do more customized things such as defining a template in the model:

#item.rb
  csv_export_columns :advanced, [{:item_id => :id}, {:name => :name}, {:description => :description}, {:status => "status.titleize"}]

 #categories_controller.rb
 wants.csv { render :text => @items.to_csv(:template => :advanced) }

This adds an import/export template named advanced to the Item model, usable in both to_csv and from_csv. In our template, we have passed an array of hashes. We pass an array to maintain positioning, each hash is a key => val pair. The key is the text to be used in the header column of the csv. The value of the hash will be the method called to populate the csv for each item. As you can see you can chain methods together (”status.titleize”). You cannot, however, call a method with arguments. If you want to format a date or similar, create a method in your model that will output the appropriate format and use that in your template call.

Instead of specifying an export template, you can also simply supply the columns you wish to export:

  @items.to_csv(:columns => [{:column1 => :some_method}, {:column_2 => :another_method}])

For more information on the plugin, there is a substantial documentation included with the source. It is rdoc format, so you can easily generate the doc locally. Please let me know if you have any questions and I’m completely open to suggestions.

Future Plans
There isn’t much that I’d like to do with this plugin at the moment.
For the 1.0 release I will be cleaning up the plugin a little bit and the API might change slightly (for template definition).
A 2.0 release, if deemed necessary, will be a completely rewrite from what I have learned, attempting to keep the API the same as the 1.0 release for reverse compatibility.
A Name change might be in order since importing has been added to the plugin

Leave a Reply