Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# 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
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.