Sha256: 8c2d55905492d2444ca658761856b12cba8326eb5281d2beed5f8c7fd6b6f1f8

Contents?: true

Size: 1.48 KB

Versions: 15

Compression:

Stored size: 1.48 KB

Contents

require 'intercom/traits/api_resource'

module Intercom
  module ApiOperations
    module Save
      PARAMS_NOT_PROVIDED = Object.new
      private_constant :PARAMS_NOT_PROVIDED

      def create(params = PARAMS_NOT_PROVIDED)
        if collection_class.ancestors.include?(Intercom::Contact) && params == PARAMS_NOT_PROVIDED
          params = Hash.new
        elsif params == PARAMS_NOT_PROVIDED
          raise ArgumentError, '.create requires 1 parameter'
        end

        instance = collection_class.new(params)
        instance.mark_fields_as_changed!(params.keys)
        save(instance)
      end

      def save(object)
        collection_name = Utils.resource_class_to_collection_name(collection_class)
        if id_present?(object) && !posted_updates?(object)
          response = @client.put("/#{collection_name}/#{object.id}", object.to_submittable_hash)
        else
          response = @client.post("/#{collection_name}", object.to_submittable_hash.merge(identity_hash(object)))
        end
        object.from_response(response) if response # may be nil we received back a 202
      end

      def identity_hash(object)
        object.respond_to?(:identity_vars) ? SliceableHash.new(object.to_hash).slice(*(object.identity_vars.map(&:to_s))) : {}
      end

      private

      def id_present?(object)
        object.id && object.id.to_s != ''
      end

      def posted_updates?(object)
        object.respond_to?(:update_verb) && object.update_verb == 'post'
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
intercom-3.5.9 lib/intercom/api_operations/save.rb
intercom-3.5.8 lib/intercom/api_operations/save.rb
intercom-3.5.7 lib/intercom/api_operations/save.rb
intercom-3.5.6 lib/intercom/api_operations/save.rb
intercom-3.5.5 lib/intercom/api_operations/save.rb
intercom-3.5.4 lib/intercom/api_operations/save.rb
intercom-3.5.3 lib/intercom/api_operations/save.rb
intercom-3.5.2 lib/intercom/api_operations/save.rb
intercom-3.5.1 lib/intercom/api_operations/save.rb
intercom-3.4.0 lib/intercom/api_operations/save.rb
intercom-3.3.0 lib/intercom/api_operations/save.rb
intercom-3.2.0 lib/intercom/api_operations/save.rb
intercom-3.1.0 lib/intercom/api_operations/save.rb
intercom-3.0.6 lib/intercom/api_operations/save.rb
intercom-3.0.5 lib/intercom/api_operations/save.rb