class JsonapiCompliable::Util::ValidationResponse

We need to know two things in the response of a persistence call:

* The model we just tried to persist
* Was the persistence successful?

This object wraps those bits of data. The call is considered unsuccessful when it adheres to the ActiveModel#errors interface, and errors is not blank. In other words, it is not successful if there were validation errors.

@attr_reader object the object we are saving

Attributes

object[R]

Public Class Methods

new(object, deserialized_params) click to toggle source

@param object the model instance we tried to save @param deserialized_params see Base#deserialized_params

# File lib/jsonapi_compliable/util/validation_response.rb, line 17
def initialize(object, deserialized_params)
  @object = object
  @deserialized_params = deserialized_params
end

Public Instance Methods

success?() click to toggle source

Check to ensure no validation errors. @return [Boolean] did the persistence call succeed?

# File lib/jsonapi_compliable/util/validation_response.rb, line 24
def success?
  all_valid?(object, @deserialized_params.relationships)
end
to_a() click to toggle source

@return [Array] the object and success state

# File lib/jsonapi_compliable/util/validation_response.rb, line 29
def to_a
  [object, success?]
end
validate!() click to toggle source
# File lib/jsonapi_compliable/util/validation_response.rb, line 33
def validate!
  unless success?
    raise ::JsonapiCompliable::Errors::ValidationError.new(self)
  end
  self
end

Private Instance Methods

all_valid?(model, deserialized_params) click to toggle source
# File lib/jsonapi_compliable/util/validation_response.rb, line 47
def all_valid?(model, deserialized_params)
  checks = []
  checks << valid_object?(model)
  deserialized_params.each_pair do |name, payload|
    if payload.is_a?(Array)
      related_objects = model.send(name)
      related_objects.each_with_index do |r, index|
        valid = valid_object?(r)
        checks << valid

        if valid
          checks << all_valid?(r, payload[index][:relationships] || {})
        end
      end
    else
      related_object = model.send(name)
      valid = valid_object?(related_object)
      checks << valid
      if valid
        checks << all_valid?(related_object, payload[:relationships] || {})
      end
    end
  end
  checks.all? { |c| c == true }
end
valid_object?(object) click to toggle source
# File lib/jsonapi_compliable/util/validation_response.rb, line 42
def valid_object?(object)
  !object.respond_to?(:errors) ||
    (object.respond_to?(:errors) && object.errors.blank?)
end