Skip to content

Instantly share code, notes, and snippets.

@stereoscott
Last active March 15, 2020 10:47
Show Gist options
  • Save stereoscott/6996507 to your computer and use it in GitHub Desktop.
Save stereoscott/6996507 to your computer and use it in GitHub Desktop.
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
@AVINASHKAUL
Copy link

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