Class: ForestLiana::ResourceUpdater

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource, params) ⇒ ResourceUpdater

Returns a new instance of ResourceUpdater.



5
6
7
8
# File 'app/services/forest_liana/resource_updater.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_updater.rb', line 3

def record
  @record
end

Instance Method Details

#performObject



10
11
12
13
14
15
16
17
18
19
20
# File 'app/services/forest_liana/resource_updater.rb', line 10

def perform
  @record = @resource.find(@params[:id])

  if Rails::VERSION::MAJOR == 4
    @record.update_attributes!(resource_params.permit!)
  else
    @record.update_attributes!(resource_params, without_protection: true)
  end

  set_has_many_relationships
end

#resource_paramsObject



22
23
24
# File 'app/services/forest_liana/resource_updater.rb', line 22

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

#set_has_many_relationshipsObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/services/forest_liana/resource_updater.rb', line 26

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