Method: Assertion.guards

Defined in:
lib/assertion.rb

.guards(attribute = nil, &block) ⇒ Class

Builds the subclass of ‘Assertion::Guard` with given attribute (alias for the `object`) and implementation of the `#state` method.

Examples:

VoterOnly = Assertion.guards :user do
  IsAdult[user.attributes] & IsCitizen[user.attributes]
end

# This is the same as:
class VoterOnly < Assertion::Guard
  alias_method :user, :object

  def state
    IsAdult[user.attributes] & IsCitizen[user.attributes]
  end
end

Parameters:

  • attribute (Symbol) (defaults to: nil)

    The alias for the ‘object` attribute

  • block (Proc)

    The content for the ‘state` method

Returns:

  • (Class)

    The specific guard class



102
103
104
105
106
107
108
# File 'lib/assertion.rb', line 102

def self.guards(attribute = nil, &block)
  klass = Class.new(Guard)
  klass.public_send(:attribute, attribute) if attribute
  klass.__send__(:define_method, :state, &block) if block_given?

  klass
end