Class: Assertion::Guard

Inherits:
Object
  • Object
show all
Extended by:
DSL::Attribute, DSL::Caller
Defined in:
lib/assertion/guard.rb

Overview

The base class for object guards

The guard defines a desired state for the object and checks if that state is valid.

Its call method either returns the guarded object, or (when its state is invalid) raises an exception

The class DSL also defines a .[] shortcut to initialize and call the guard for given object immediately.

Examples:

class AdultOnly < Assertion::Guard
  alias_method :user, :object

  def state
    IsAdult[user.attributes]
  end
end

jack = User.new name: "Jack", age: 10
john = User.new name: "John", age: 59

AdultOnly[jack]
# => #<Assertion::InvalidError @messages=["Jack is a child (age 10)"]>
AdultOnly[john]
# => #<User @name="John", @age=59>

Class Method Summary collapse

Methods included from DSL::Attribute

attribute, extended

Methods included from DSL::Caller

[]

Class Method Details

.callObject

Validates the state of the [#object] and returns valid object back

Raises:



58
59
60
61
# File 'lib/assertion/guard.rb', line 58

def call
  state.validate!
  object
end

.initialize(object) ⇒ Object



47
48
49
50
# File 'lib/assertion/guard.rb', line 47

def initialize(object)
  @object = object
  freeze
end

.new(object) ⇒ Assertion::Guard

Creates the guard instance for the provided object

Parameters:

  • object (Object)

Returns:



# File 'lib/assertion/guard.rb', line 38