Last active
March 15, 2020 10:47
-
-
Save stereoscott/6996507 to your computer and use it in GitHub Desktop.
Stream CSV exports in ActiveAdmin in Rails 4
This file contains 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
# if you want to monkey patch every controller, put this in initializers/active_admin.rb | |
ActiveAdmin::ResourceController.class_eval do | |
include ActiveAdmin::CSVStream | |
end |
This file contains 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
# 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 |
This file contains 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
#admin/users.rb to use in a single controller | |
ActiveAdmin.register User do | |
controller do | |
include ActiveAdmin::CSVStream | |
end | |
end |
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
Hi! I no understand how add the 1 and 2 gist in my project.