Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stream CSV exports in ActiveAdmin in Rails 4
# if you want to monkey patch every controller, put this in initializers/active_admin.rb
ActiveAdmin::ResourceController.class_eval do
include ActiveAdmin::CSVStream
end
# put in an autoloaded path, like lib/active_admin
require 'csv'
module ActiveAdmin
module CSVStream
# using ActionController::Live breaks warden
# see https://github.com/plataformatec/devise/issues/2332
# include ActionController::Live
def apply_pagination(chain)
chain = super unless formats.include?(:csv)
chain
end
def index
index! do |format|
format.csv { render_csv }
end
end
private
def render_csv
set_csv_headers
self.response_body = csv_lines
end
def set_csv_headers
headers["Content-Type"] = "text/csv"
end
def csv_lines
default = ActiveAdmin.application.csv_options
options = default.merge active_admin_config.csv_builder.options
columns = active_admin_config.csv_builder.columns
Enumerator.new do |y|
CSV.generate(options) do |csv|
y << columns.map(&:name).to_csv
#response.stream.write columns.map(&:name).to_csv
collection.each do |resource|
row = columns.map do |column|
call_method_or_proc_on resource, column.data
end.to_csv
y << row
#response.stream.write row
end
end
end
#response.stream.close
end
end
end
#admin/users.rb to use in a single controller
ActiveAdmin.register User do
controller do
include ActiveAdmin::CSVStream
end
end
@luiszacheu

This comment has been minimized.

Copy link

commented Oct 28, 2016

Hi! I no understand how add the 1 and 2 gist in my project.

@AVINASHKAUL

This comment has been minimized.

Copy link

commented Mar 8, 2019

I am getting following error "Unknown options: byte_order_mark."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.