Last active
August 29, 2015 14:24
-
-
Save Jamedjo/cf11f3d3662f9ce6e9ca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
ActionController::Renderers.add :csv do |collection, options| | |
self.content_type ||= Mime::CSV | |
self.headers['Content-Disposition'] = "attachment; filename=#{options[:filename]}.csv" if options[:filename] | |
self.response_body = collection.to_csv | |
end | |
module CsvRenderer | |
def to_csv(options={}) | |
columns = column_names | |
columns += options[:include] if options[:include] | |
CSV.generate do |csv| | |
csv << columns | |
all.pluck(*columns).each do |row| | |
csv << row | |
end | |
end | |
end | |
end | |
ActiveRecord::Base.extend CsvRenderer |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Item < ActiveRecord::Base | |
def self.to_csv | |
super(include: [:username, :first_name]) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ItemsController < OpsController | |
respond_to :json, :csv | |
def index | |
respond_with(Item.joins(:user), filename: "items") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment