Skip to content
forked from arydjmal/to_csv

This simple plugin gives you the ability to call to_csv to a collection of activerecords. The builder options are the same as to_json / to_xml, except for the :include.

License

Notifications You must be signed in to change notification settings

phlawski/to_csv

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

to_csv plugin

This simple plugin gives you the ability to call to_csv to a collection of activerecords. The builder options are the same as to_json / to_xml, except for the :include.

Fork

This fork just provides ability to use I18n translated column headers. It simply takes translations from localized yaml templates for ActiveRecord models. Additionaly it is possible to add translations for extra columns added by plugin’s :methods option - i.e. by using :methods => [{:user => :name}]) plugin produces user_name column header, so adding user_name: Here your translation in localized yaml file for correct model will do the trick.

Usage

@users = User.all

#
# defaults are export header and all fields except id, and timestamps
#

@users.to_csv
@users.to_csv(:only => [:last_name, :role])
@users.to_csv(:timestamps => true, :id => true, :header => false)
@users.to_csv(:except => [:last_name, :role])
@users.to_csv(:except => :role, :methods => [:name, :admin?])

#
# NEW FEATURE
# Now you can call methods of a has_one or belongs_to association
# (for now you can go up/down 1 level)
#

# A note belongs_to :user
@notes = Note.all
@notes.to_csv(:methods => [{:user => :name}])

Real life example

In the controller where you want to export to csv, add the format.csv line (as of rails 2.1 it is not necessary to register the csv myme_type)

class UserController < ApplicationController

def index @users = User.all

respond_to do |format| format.html format.xml { render :xml => @users } format.csv { send_data @users.to_csv } end end

def show… def new… def edit… def create… def update… def destroy…

end

Dependencies

sudo gem install fastercsv

Install

./script/plugin install git://github.com/arydjmal/to_csv.git

Ideas

I got ideas and influence from Mike Clarks recipe #35 in Rails Recipes book, some anonymous pastie, and whoever wrote to_xml/to_json builders.

Note

Does not work on a single activerecord, ie, User.first.to_csv. Cannot style output.

Copyright © 2008 Ary Djmal, released under the MIT license

About

This simple plugin gives you the ability to call to_csv to a collection of activerecords. The builder options are the same as to_json / to_xml, except for the :include.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Ruby 100.0%