@@ -25,6 +25,22 @@ module ActiveAdminImport
2525 # +plural_resource_label+:: pluralized resource label value (default config.plural_resource_label)
2626 #
2727 module DSL
28+ CONTEXT_METHOD = :active_admin_import_context
29+
30+ def self . prepare_import_model ( template_object , controller , params : nil )
31+ model = template_object . is_a? ( Proc ) ? template_object . call : template_object
32+ if params
33+ params_key = ActiveModel ::Naming . param_key ( model . class )
34+ model . assign_attributes ( params [ params_key ] . try ( :deep_symbolize_keys ) || { } )
35+ end
36+ return model unless controller . respond_to? ( CONTEXT_METHOD , true )
37+ context = controller . send ( CONTEXT_METHOD )
38+ return model unless context . is_a? ( Hash )
39+ context = context . merge ( file : model . file ) if model . respond_to? ( :file ) && !context . key? ( :file )
40+ model . assign_attributes ( context )
41+ model
42+ end
43+
2844 DEFAULT_RESULT_PROC = lambda do |result , options |
2945 model_name = options [ :resource_label ] . downcase
3046 plural_model_name = options [ :plural_resource_label ] . downcase
@@ -57,11 +73,7 @@ def active_admin_import(options = {}, &block)
5773
5874 collection_action :import , method : :get do
5975 authorize! ( ActiveAdminImport ::Auth ::IMPORT , active_admin_config . resource_class )
60- @active_admin_import_model = if options [ :template_object ] . is_a? ( Proc )
61- options [ :template_object ] . call
62- else
63- options [ :template_object ]
64- end
76+ @active_admin_import_model = ActiveAdminImport ::DSL . prepare_import_model ( options [ :template_object ] , self )
6577 render template : options [ :template ]
6678 end
6779
@@ -78,13 +90,9 @@ def active_admin_import(options = {}, &block)
7890 authorize! ( ActiveAdminImport ::Auth ::IMPORT , active_admin_config . resource_class )
7991 _params = params . respond_to? ( :to_unsafe_h ) ? params . to_unsafe_h : params
8092 params = ActiveSupport ::HashWithIndifferentAccess . new _params
81- @active_admin_import_model = if options [ :template_object ] . is_a? ( Proc )
82- options [ :template_object ] . call
83- else
84- options [ :template_object ]
85- end
86- params_key = ActiveModel ::Naming . param_key ( @active_admin_import_model . class )
87- @active_admin_import_model . assign_attributes ( params [ params_key ] . try ( :deep_symbolize_keys ) || { } )
93+ @active_admin_import_model = ActiveAdminImport ::DSL . prepare_import_model (
94+ options [ :template_object ] , self , params : params
95+ )
8896 # go back to form
8997 return render template : options [ :template ] unless @active_admin_import_model . valid?
9098 @importer = Importer . new (
0 commit comments