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



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

#performObject



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

def perform
  @record = @resource.create(resource_params)
  set_has_many_relationships
end

#resource_paramsObject



15
16
17
# File 'app/services/forest_liana/resource_creator.rb', line 15

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

#set_has_many_relationshipsObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'app/services/forest_liana/resource_creator.rb', line 19

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