= CsvRails

CsvRails provides a simple way of download csv in Rails 3.

== Install

To use CsvRails simply add the line

    gem 'csv_rails'

to your Gemfile and then run

    bundle install

== Example

    class UsersController < ApplicationController
      def index
        @users = User.all

        respond_to do |format|
          format.html { @users = @users.all }
          format.json { render json: @users }
          format.csv{ render csv: @users, fields: [:id, :name, :age], encoding: 'SJIS', without_header: true }
        end
      end


== Usage

If you want formatted attribute, CsvRails call "#{attribute}_as_csv". For example, you wish formatted created_at then you write like this. 

    class User < ActiveRecord::Base
      def created_at_as_csv
        created_at.strftime("%F %H:%M")
      end
    end

CsvRails define a singleton method Array.to_csv, and the method accept fields option. The fields option can not only database fields also method and method chain.

    class User < ActiveRecord::Base
      has_many :memberships
      has_many :groups, through: :memberships

      def ok
        "OK"
      end
    end

    class UsersController < ApplicationController
      def index
        @users = User.all

        respond_to do |format|
          format.csv{ render csv: @users, fields: [:ok, :"groups.first.name"], encoding: 'SJIS' }
        end
      end

If you do not use :header option, header is using :fields and I18n transfer.
    # config/locales/ja.yml
    ja:
      activerecord:
        attributes:
          group: &groupmodel
            name: グループ名
          user:
            id: ID
            name: 名前
            age: 年齢
            ok: OK
          # rails3
            groups:
              first:
                <<: *groupmodel
          # edge rails
          user/groups:
            first:
              <<: *groupmodel


    # app/controllers/user_controller.rb
    def index
      @users = User.where("id < 1").all
      respond_to do |format|
        format.csv{ render csv: @users, fields: [:ok, :"groups.first.name"], encoding: 'SJIS' } #=> "OK,グループ名"
      end
    end

You also use i18n_scope option
    # config/locales/ja.yml
    ja:
      csv:
        name: なまえ

    User.where("id < 1").all.to_csv(:i18n_scope => :csv) #=> "なまえ\n"

Copyright (c) 2012 yalab, released under the MIT license