Sha256: 06a1405b527a49d4c164a57dd928c760ee9424da34e8e2b1d48c50fa1275b533

Contents?: true

Size: 1.36 KB

Versions: 14

Compression:

Stored size: 1.36 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 has_strong_parameter
        @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

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

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
forest_liana-1.3.40 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.39 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.38 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.37 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.36 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.35 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.34 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.33 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.32 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.31 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.30 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.29 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.28 app/services/forest_liana/resource_updater.rb
forest_liana-1.3.27 app/services/forest_liana/resource_updater.rb