Sha256: f2e544760acb8c178b2e067aa5dd310321231c428e4ede2df5a184cfa1885f41

Contents?: true

Size: 1.3 KB

Versions: 6

Compression:

Stored size: 1.3 KB

Contents

module ForestLiana
  class ResourceUpdater
    attr_accessor :record

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

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

      if @resource.instance_method(:update_attributes!).arity == 1
        @record.update_attributes!(resource_params)
      else
        @record.update_attributes!(resource_params, without_protection: true)
      end

      set_has_many_relationships
    end

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

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

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
forest_liana-1.3.5 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.4 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.3 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.2 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.1 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.0 app/services/forest_liana/resource_updater.rb