Class: Restspec::Schema::Checker::ObjectChecker

Inherits:
Object
  • Object
show all
Defined in:
lib/restspec/schema/checker.rb

Overview

Checks an object against a schema's attribute definition.

Instance Method Summary collapse

Constructor Details

#initialize(object, attribute) ⇒ ObjectChecker

Returns a new instance of ObjectChecker


44
45
46
47
# File 'lib/restspec/schema/checker.rb', line 44

def initialize(object, attribute)
  self.object = object
  self.attribute = attribute
end

Instance Method Details

#check_invalid!Object

Calls #invalid? and if the call is true, raises a InvalidationError.

Raises:


96
97
98
# File 'lib/restspec/schema/checker.rb', line 96

def check_invalid!
  raise InvalidationError.new(object, attribute) if invalid?
end

#check_missed_key!Object

Calls #missed_key? and if the call is true, raises a NoAttributeError.

Raises:


69
70
71
# File 'lib/restspec/schema/checker.rb', line 69

def check_missed_key!
  raise NoAttributeError.new(object, attribute) if missed_key?
end

#invalid?true, false

Checks if the attribute's type validation fails with the object' attribute. To do this, the #valid? method of the type is executed.

Examples:

# Given the following schema
schema :product do
  attribute :name, string
end

ObjectChecker.new({ name: 10 }, schema.attributes[:name]).invalid?
# true
ObjectChecker.new({ name: 'John' }, schema.attributes[:name]).invalid?
# false

Returns:

  • (true, false)

    If the attribute's type validation fails with the object' attribute.


90
91
92
# File 'lib/restspec/schema/checker.rb', line 90

def invalid?
  !attribute.type.totally_valid?(attribute, object.fetch(attribute.name))
end

#missed_key?true, false

Checks if the attribute's key is absent from the object.

Examples:

# Given the following schema
schema :product do
  attribute :name, string
end

ObjectChecker.new({ age: 10 }, schema.attributes[:name]).missed_key?
# true
ObjectChecker.new({ name: 'John' }, schema.attributes[:name]).missed_key?
# false

Returns:

  • (true, false)

    If the attribute's key is absent from the object


63
64
65
# File 'lib/restspec/schema/checker.rb', line 63

def missed_key?
  !object.has_key?(attribute.name)
end