Sha256: a73e48aabf984ef1ff676ce30b58219452233442afddd39ab35cfa98860ea72a

Contents?: true

Size: 1.42 KB

Versions: 62

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

require 'active_support'

class LHS::Item < LHS::Proxy
  autoload :EndpointLookup,
    'lhs/concerns/item/endpoint_lookup'

  module Save
    extend ActiveSupport::Concern

    included do
      include EndpointLookup
    end

    def save(options = nil)
      save!(options)
    rescue LHC::Error
      false
    end

    def save!(options = {})
      options = options.present? ? options.dup : {}
      data = _data._raw.dup
      url = url_for_persistance!(data, options)
      create_and_merge_data!(
        apply_default_creation_options(options, url, data)
      )
    rescue LHC::Error => e
      self.errors = LHS::Problems::Errors.new(e.response, record)
      raise e
    end

    private

    def apply_default_creation_options(options, url, data)
      options = options.merge(method: :post, url: url, body: data)
      options[:headers] ||= {}
      options
    end

    def create_and_merge_data!(options)
      response_data = record.request(options)
      if response_data.present?
        _data.merge_raw!(response_data.unwrap(:item_created_key))
        response_headers = response_data._request.response.headers
      end
      if response_headers && response_headers['Location']
        location_data = record.request(options.merge(url: response_headers['Location'], method: :get, body: nil))
        _data.merge_raw!(location_data.unwrap(:item_created_key))
      end
      true
    end
  end
end

Version data entries

62 entries across 62 versions & 1 rubygems

Version Path
lhs-20.1.2 lib/lhs/concerns/item/save.rb
lhs-20.1.1 lib/lhs/concerns/item/save.rb
lhs-20.0.0 lib/lhs/concerns/item/save.rb
lhs-19.10.0 lib/lhs/concerns/item/save.rb
lhs-19.9.0 lib/lhs/concerns/item/save.rb
lhs-19.8.2 lib/lhs/concerns/item/save.rb
lhs-19.8.1 lib/lhs/concerns/item/save.rb
lhs-19.8.0 lib/lhs/concerns/item/save.rb
lhs-19.7.0 lib/lhs/concerns/item/save.rb
lhs-19.6.0 lib/lhs/concerns/item/save.rb
lhs-19.5.0 lib/lhs/concerns/item/save.rb
lhs-19.5.0.pre.wherehref.1 lib/lhs/concerns/item/save.rb
lhs-19.4.1 lib/lhs/concerns/item/save.rb
lhs-19.4.0 lib/lhs/concerns/item/save.rb
lhs-19.3.1 lib/lhs/concerns/item/save.rb
lhs-19.3.0 lib/lhs/concerns/item/save.rb
lhs-19.2.0 lib/lhs/concerns/item/save.rb
lhs-19.1.0 lib/lhs/concerns/item/save.rb
lhs-19.0.2 lib/lhs/concerns/item/save.rb
lhs-19.0.1 lib/lhs/concerns/item/save.rb