No commit activity in last 3 years
No release in over 3 years
Add custom csv renderer for Rails application
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.3
~> 10.1.1
~> 3.0.0

Runtime

>= 4.0
 Project Readme

rails_csv_renderer

Build Status Code Climate Gem Version

Custom CSV renderer for ActiveRecord collections

Installation

Add this line to your application's Gemfile:

gem 'rails_csv_renderer'

And then execute:

$ bundle

Or install it yourself as:

$ gem install rails_csv_renderer

Usage

The rails_csv_renderer allows you to render any collection as CSV data. Result CSV includes all columns of model with localized column's names

class ReportsController < ApplicationController
  def index
    @reports = Report.all

    respond_to do |format|
      format.csv  { render csv: @reports }
    end
  end
end

Will render a CSV file similar to:

Title Content Created at Updated at
House report Report about house devices 2014-07-14 01:00:42 UTC 2014-07-14 01:00:42 UTC
Work report Report about work devices 2014-07-14 12:42:42 UTC 2014-07-14 12:42:42 UTC

Options

You can pass few options at call of rendrer:

  • :filename - Name of file. Optional
  • :csv_options - Options for CSV generator. Availible options. Optional
  • :columns - Array of variables and methods. Title of columns will be created based on your translations. In this case you should not define methods in model. Optional

Example

class ReportsController < ApplicationController
  def index
    @reports = Report.all

    respond_to do |format|
      format.csv  { render csv: @reports, filename: 'custom-reports.csv', csv_options: { col_sep: '\t' }, columns: [:created_at, :title] }
    end
  end
end

Localize column's names

If you have translations for model's attributes under scope [:activerecord, :attributes, *model_name*] names of columns will be automatically translated.

Customize CSV

To customize your CSV file with different methods and name of columns you should add next methods to model csv_header(class method), csv_row.

  • csv_header should return array with column's titles.

  • csv_row should return array with values for columns.

class Cat < ActiveRecord::Base
  def self.csv_header
    ["ID", "Cat's name"]
  end

  def csv_row
    [id, name]
  end
end

Contributing

  1. Fork it ( https://github.com/[my-github-username]/rails_csv_renderer/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request