Last active
December 14, 2022 13:37
-
-
Save darrenterhune/a58ec2e6e3ff83b8a0b7c2b9e937a071 to your computer and use it in GitHub Desktop.
Simple activeadmin export full table csv using a sidekiq background worker
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
# app/workers/active_admin_export_worker.rb | |
class ActiveAdminExportWorker | |
include Sidekiq::Worker | |
sidekiq_options queue: 'high' | |
def perform(options = {}) | |
model = options[:model_name].classify.constantize | |
path = "#{Rails.root.to_s}/tmp/#{filename(options[:name])}" | |
columns = model.send(:column_names) | |
CSV.open(path, 'wb', headers: true) do |csv| | |
csv << columns | |
model.select(columns).find_each do |m| | |
csv << m.attributes.values | |
end | |
end | |
end | |
private | |
def filename(model) | |
[model.to_s.try(:downcase), Time.current.try(:to_i)].join('_') + '.csv' | |
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
# config/initializers/active_admin_extensions.rb | |
# Simple modified version of https://gist.github.com/stereoscott/6996507 | |
module ActiveAdmin | |
module Reports | |
module DSL | |
def enable_reports | |
action_item only: :index do | |
link_to 'Download', { action: :download, params: params }, { method: :post, data: { confirm: 'Are you sure you want to generate this report?' } } | |
end | |
collection_action :download, method: :post do | |
options = { | |
name: resource_class.to_s.pluralize, | |
model_name: resource_class.to_s, | |
email: current_admin_user.email | |
} | |
# User perform_later or perform_now for new versions of sidekiq | |
ActiveAdminExportWorker.perform_async(options) | |
redirect_to :back | |
end | |
end | |
end | |
end | |
ActiveAdmin::ResourceDSL.send :include, ActiveAdmin::Reports::DSL | |
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
# app/admin/users.rb | |
# Add "enable_reports" to which ever activeadmin resource you want, this will add the download link on the top right | |
ActiveAdmin.register User do | |
enable_reports | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment