Module: Assertion

Defined in:
lib/assertion.rb,
lib/assertion/base.rb,
lib/assertion/guard.rb,
lib/assertion/state.rb,
lib/assertion/inverter.rb,
lib/assertion/messages.rb,
lib/assertion/inversion.rb,
lib/assertion/attributes.rb,
lib/assertion/invalid_error.rb,
lib/assertion/transprocs/list.rb,
lib/assertion/transprocs/inflector.rb

Overview

The module allows declaring assertions (assertions) about various objects, and apply (validate) them to concrete data.

Examples:

# config/locales/en.yml
# ---
# en:
#   assertion:
#     adult:
#       right: "%{name} is an adult (age %{age})"
#       wrong: "%{name} is a child (age %{age})"

Adult = Assertion.about :name, :age do
  age >= 18
end

joe = { name: 'Joe', age: 13 }
Adult[joe].validate!
# => #<Assertion::InvalidError @messages=["Joe is a child (age 13)"]>

jane = { name: 'Jane', age: 22 }
Adult.not[jane].validate!
# => #<Assertion::InvalidError @messages=["Jane is an adult (age 22)"]

Defined Under Namespace

Modules: Attributes, Inflector, List, Messages Classes: Base, Guard, InvalidError, Inversion, Inverter, State

Class Method Summary collapse

Class Method Details

.about(*attributes, &block) ⇒ Class

Builds the subclass of ‘Assertion::Base` with predefined `attributes` and implementation of the `#check` method.

Examples:

IsMan = Assertion.about :age, :gender do
  (age >= 18) && (gender == :male)
end

# This is the same as:
class IsMan < Assertion::Base
  attribute :age, :gender

  def check
    (age >= 18) && (gender == :male)
  end
end

Parameters:

  • attributes (Symbol, Array<Symbol>)

    The list of attributes for the new assertion

  • block (Proc)

    The content for the ‘check` method

Returns:

  • (Class)

    The specific assertion class



70
71
72
73
74
75
76
# File 'lib/assertion.rb', line 70

def self.about(*attributes, &block)
  klass = Class.new(Base)
  klass.public_send(:attribute, attributes)
  klass.__send__(:define_method, :check, &block) if block_given?

  klass
end

.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