Sha256: c5be42bd4513593ed6ebdda33b4f8d81dafce7af4ffc21618f67f1f51cdcd908

Contents?: true

Size: 1.79 KB

Versions: 7

Compression:

Stored size: 1.79 KB

Contents

require 'active_support'

class LHS::Item < LHS::Proxy

  module Validation
    extend ActiveSupport::Concern

    def valid?(options = {})
      options ||= {}
      errors.clear
      endpoint = validation_endpoint
      raise 'No endpoint found to perform validations! See here: https://github.com/local-ch/lhs#validation' unless endpoint
      record = LHS::Record.for_url(endpoint.url)
      params = merge_validation_params!(endpoint).merge options.fetch(:params, {})
      url = validation_url(endpoint)
      run_validation!(record, options, url, params)
      true
    rescue LHC::Error => e
      self.errors = LHS::Errors.new(e.response)
      false
    end
    alias validate valid?

    private

    def validation_url(endpoint)
      url = endpoint.url
      action = endpoint.options[:validates][:path].presence
      url = "#{url}/#{action}" if action.present?
      url
    end

    def merge_validation_params!(endpoint)
      validates_params = endpoint.options[:validates].select { |key, _| key.to_sym != :path }
      params = endpoint.options.fetch(:params, {}).merge(params_from_link)
      params = params.merge(validates_params) if validates_params.is_a?(Hash)
      params
    end

    def run_validation!(record, options, url, params)
      record.request(
        options.merge(
          url: url,
          method: :post,
          params: params,
          body: _data.to_json,
          headers: { 'Content-Type' => 'application/json' }
        )
      )
    end

    def validation_endpoint
      endpoint = endpoint_from_link if _data.href # take embeded first
      endpoint ||= _data._record.find_endpoint(_data._raw)
      validates = endpoint.options && endpoint.options.fetch(:validates, false)
      raise 'Endpoint does not support validations!' unless validates
      endpoint
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
lhs-11.0.3 lib/lhs/concerns/item/validation.rb
lhs-11.0.2 lib/lhs/concerns/item/validation.rb
lhs-11.0.1 lib/lhs/concerns/item/validation.rb
lhs-11.0.0 lib/lhs/concerns/item/validation.rb
lhs-10.1.1 lib/lhs/concerns/item/validation.rb
lhs-10.1.0 lib/lhs/concerns/item/validation.rb
lhs-10.0.0 lib/lhs/concerns/item/validation.rb