Rails renderers
- CSV renderer for ActiveRecord collections
- ZIP renderer fo collection of File objects
Big thanks to @beerlington and his render_csv gem.
Rails: 3.0.x - 4.0.x
Ruby: 1.9.3, 2.0.0 and 2.1.0
Add this line to your application's Gemfile:
gem 'useful_renderers'
And then execute:
$ bundle
Or install it yourself as:
$ gem install useful_renderers
The CSV renderer allows you to render any collection as CSV data.
class LocationsController < ApplicationController
def index
@locations = Location.all
respond_to do |format|
format.csv { render csv: @locations }
end
end
end
Will render a CSV file similar to:
name | address | city | state | zip | created_at | updated_at |
---|---|---|---|---|---|---|
Pete's House | 555 House Ln | Burlington | VT | 05401 | 2011-07-26 03:12:44 UTC | 2011-07-26 03:12:44 UTC |
Sebastians's House | 123 Pup St | Burlington | VT | 05401 | 2011-07-26 03:30:44 UTC | 2011-07-26 03:30:44 UTC |
Someone Else | 999 Herp Derp | Burlington | VT | 05401 | 2011-07-26 03:30:44 UTC | 2011-07-26 03:30:44 UTC |
There are a few options you can use to customize which columns are included in the CSV file
respond_to do |format|
format.csv { render csv: @locations, except: [:id] }
end
respond_to do |format|
format.csv { render csv: @locations, only: [:address, :zip, 'country.state'] }
end
Using Class.human_attribute_name(column_name)
respond_to do |format|
format.csv { render csv: @locations, translate: true }
end
- Fork it ( https://github.com/blueberryapps/useful_renderers/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Rails CSV renderer for ActiveRecord collections
Copyright © 2011-2014 Peter Brown. See LICENSE.txt for render_csv. Copyright © 2014 Ondrej Bartas for implementation ZIP and updates of render_csv.