Class: Handlers::Polymorph
Instance Method Summary collapse
- #form_class ⇒ Object
- #handle ⇒ Object
-
#initialize(klass, polymorph) ⇒ Polymorph
constructor
Handle either the retrieving of the associated relation or the creation of the resource based on this possible input and the params.
Methods inherited from Base
Constructor Details
#initialize(klass, polymorph) ⇒ Polymorph
Handle either the retrieving of the associated relation or the creation of the resource based on this possible input and the params
Params:
klass
-
ActiveFormObject::Base instance
polymorph
-
The param specified in the dsl, example :
{
key: :content,
foreign_key: :program_id,
types: {
polymorph: Dsl::PolymorphsTest::PolymorphForeignForm
}
}
29 30 31 32 33 |
# File 'lib/handlers/polymorphs.rb', line 29 def initialize(klass, polymorph) @polymorph = polymorph super(klass) end |
Instance Method Details
#form_class ⇒ Object
48 49 50 51 52 53 54 |
# File 'lib/handlers/polymorphs.rb', line 48 def form_class @type = @resource.try(@polymorph[:key]).try(:type) || @params_to_send['type'] raise_error("No 'type' method or 'type‘ key found in params for '#{@polymorph[:key]}' polymorphic relation") if @type.nil? @params_to_send.delete(:type) @polymorph[:types][@type.try(:to_sym)] end |
#handle ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/handlers/polymorphs.rb', line 35 def handle @params_to_send = @params[@polymorph[:key]] || {} form = form_class raise_error("The form resolved with key '#{@type}' seems to be nil. Check your polymorphic relation key and the associated forms.") if form.nil? polymorph_instance = form.new(@params_to_send, @resource.try(@polymorph[:key])).save! @params["#{@polymorph[:key]}_id"] = polymorph_instance.id @params["#{@polymorph[:key]}_type"] = polymorph_instance.class.name @params.delete(@polymorph[:key]) end |