Sha256: 419211a479671ccaf606953a101f0150d8ed08e4f7652895bbfe6def2c220862

Contents?: true

Size: 1.29 KB

Versions: 10

Compression:

Stored size: 1.29 KB

Contents

require 'active_support'

class LHS::Item < LHS::Proxy

  module Validation
    extend ActiveSupport::Concern

    def valid?(options = {})
      options ||= {}
      self.errors = nil
      fail 'No validation endpoint found!' unless validation_endpoint
      record = LHS::Record.for_url(validation_endpoint.url)
      validation_params = validation_endpoint.options[:validates] == true ? { persist: false } : { validation_endpoint.options[:validates] => false }
      params = validation_endpoint.options.fetch(:params, {}).merge(validation_params)
      begin
        record.request(
          options.merge(
            url: validation_endpoint.url,
            method: :post,
            params: params,
            body: _data.to_json,
            headers: { 'Content-Type' => 'application/json' }
          )
        )
        true
      rescue LHC::Error => e
        self.errors = LHS::Errors.new(e.response)
        false
      end
    end
    alias validate valid?

    private

    def validation_endpoint
      endpoint = _data._record.find_endpoint(_data._raw)
      endpoint ||= LHS::Endpoint.for_url(_data.href) if _data.href
      validates = endpoint.options && endpoint.options.fetch(:validates, false)
      fail 'Endpoint does not support validations!' unless validates
      endpoint
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
lhs-5.6.2 lib/lhs/concerns/item/validation.rb
lhs-5.6.1 lib/lhs/concerns/item/validation.rb
lhs-5.6.0 lib/lhs/concerns/item/validation.rb
lhs-5.5.0 lib/lhs/concerns/item/validation.rb
lhs-5.4.2 lib/lhs/concerns/item/validation.rb
lhs-5.4.1 lib/lhs/concerns/item/validation.rb
lhs-5.4.0 lib/lhs/concerns/item/validation.rb
lhs-5.3.0 lib/lhs/concerns/item/validation.rb
lhs-5.2.0 lib/lhs/concerns/item/validation.rb
lhs-5.1.0 lib/lhs/concerns/item/validation.rb