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.



49
50
51
52
# File 'lib/restspec/schema/checker.rb', line 49

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:



101
102
103
# File 'lib/restspec/schema/checker.rb', line 101

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:



74
75
76
# File 'lib/restspec/schema/checker.rb', line 74

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.



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

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



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

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