Class: ForestLiana::ResourceCreator
- Inherits:
-
Object
- Object
- ForestLiana::ResourceCreator
- Defined in:
- app/services/forest_liana/resource_creator.rb
Instance Attribute Summary collapse
-
#errors ⇒ Object
Returns the value of attribute errors.
-
#record ⇒ Object
Returns the value of attribute record.
Instance Method Summary collapse
- #has_strong_parameter ⇒ Object
-
#initialize(resource, params) ⇒ ResourceCreator
constructor
A new instance of ResourceCreator.
- #perform ⇒ Object
- #resource_params ⇒ Object
- #set_has_many_relationships ⇒ Object
Constructor Details
#initialize(resource, params) ⇒ ResourceCreator
Returns a new instance of ResourceCreator.
6 7 8 9 10 |
# File 'app/services/forest_liana/resource_creator.rb', line 6 def initialize(resource, params) @resource = resource @params = params @errors = nil end |
Instance Attribute Details
#errors ⇒ Object
Returns the value of attribute errors.
4 5 6 |
# File 'app/services/forest_liana/resource_creator.rb', line 4 def errors @errors end |
#record ⇒ Object
Returns the value of attribute record.
3 4 5 |
# File 'app/services/forest_liana/resource_creator.rb', line 3 def record @record end |
Instance Method Details
#has_strong_parameter ⇒ Object
55 56 57 |
# File 'app/services/forest_liana/resource_creator.rb', line 55 def has_strong_parameter Rails::VERSION::MAJOR > 5 || @resource.instance_method(:update!).arity == 1 end |
#perform ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'app/services/forest_liana/resource_creator.rb', line 12 def perform begin if has_strong_parameter @record = @resource.create(resource_params) else @record = @resource.create(resource_params, without_protection: true) end set_has_many_relationships rescue ActiveRecord::StatementInvalid => exception # NOTICE: SQLÂ request cannot be executed properly @errors = [{ detail: exception.cause.error }] rescue ForestLiana::Errors::SerializeAttributeBadFormat => exception @errors = [{ detail: exception. }] rescue => exception @errors = [{ detail: exception. }] end end |
#resource_params ⇒ Object
30 31 32 |
# File 'app/services/forest_liana/resource_creator.rb', line 30 def resource_params ResourceDeserializer.new(@resource, @params, true).perform end |
#set_has_many_relationships ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'app/services/forest_liana/resource_creator.rb', line 34 def set_has_many_relationships if @params['data']['relationships'] @params['data']['relationships'].each do |name, relationship| data = relationship['data'] association = @resource.reflect_on_association(name.to_sym) if [:has_many, :has_and_belongs_to_many].include?( association.try(:macro)) if data.is_a?(Array) data.each do |x| existing_records = @record.send(name) new_record = association.klass.find(x[:id]) if !existing_records.include?(new_record) existing_records << new_record end end end end end end end |