Class: ForestLiana::ResourceCreator

Inherits:
Object
  • Object
show all
Defined in:
app/services/forest_liana/resource_creator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource, params) ⇒ ResourceCreator

Returns a new instance of ResourceCreator.



5
6
7
8
# File 'app/services/forest_liana/resource_creator.rb', line 5

def initialize(resource, params)
  @resource = resource
  @params = params
end

Instance Attribute Details

#recordObject

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_parameterObject



44
45
46
# File 'app/services/forest_liana/resource_creator.rb', line 44

def has_strong_parameter
  @resource.instance_method(:update_attributes!).arity == 1
end

#performObject



10
11
12
13
14
15
16
17
# File 'app/services/forest_liana/resource_creator.rb', line 10

def perform
  if has_strong_parameter
    @record = @resource.create(resource_params)
  else
    @record = @resource.create(resource_params, without_protection: true)
  end
  set_has_many_relationships
end

#resource_paramsObject



19
20
21
# File 'app/services/forest_liana/resource_creator.rb', line 19

def resource_params
  ResourceDeserializer.new(@resource, @params[:resource]).perform
end

#set_has_many_relationshipsObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'app/services/forest_liana/resource_creator.rb', line 23

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)
      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