Module: ActiveAdminSimpleImport::DSL

Defined in:
lib/active_admin_simple_import/dsl.rb

Instance Method Summary collapse

Instance Method Details

#active_admin_import(options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/active_admin_simple_import/dsl.rb', line 3

def active_admin_import(options = {})
  options = { exclusion_list: [], after_update: nil }
            .merge options

  collection_action :import, method: :get do
    render template: 'active_admin_simple_import/import'
  end

  collection_action :do_import, method: :post do
    rows = CSV.read params[:csv][:file].tempfile
    attrs = rows.shift.map{ |a| a.parameterize('_').to_sym }
    object_class = controller_name.singularize.camelize.constantize
    objects = rows.map{ |row| Hash[*attrs.zip(row).flatten] }
    objects.each do |object|
      edited_object = object_class.find object.delete :id
      edited_object.update_attributes object.except(*options[:exclusion_list])
      next if options[:after_update].nil? || !options[:after_update].is_a?(Proc)
      options[:after_update].call(edited_object, object)
    end
    redirect_to params[:csv][:redirect_to], notice: t('active_admin_simple_import.import_success', count: objects.count)
  end

  action_item :import, only: :index do
    link_to (I18n.t("active_admin_simple_import.import_button") << " #{controller_name.singularize.camelize.constantize.model_name.human}"),
            action: :import, redirect_to: request.fullpath
  end
end