Class: Aspect::Verifier::Check

Inherits:
Object
  • Object
show all
Extended by:
HasRegistry
Defined in:
lib/aspect/verifier/check.rb

Overview

A single verification check.

To define a new check, you must first register it, then define an attribute for it on the Aspect::Verifier class.

If the check’s block returns a falsey value or raises an error, the check is considered failed. When a truthy value is return, the check has passed.

Examples:

Basic usage.

require "aspect/verifier/check"

check = Aspect::Verifier::Check[:greater_than_or_equal_to]

loop do
  age = gets

  if check.call(age, 18)
    puts "Welcome!"

    break
  else
    puts "Must be 18 or older"
  end
end

Defining a new Aspect::Verifier check.

require "aspect/verifier"

Aspect::Verifier::Check.register(:length_of_at_least) { |value, expectation| value.length >= expectation }
Aspect::Verifier.attribute(:length_of_at_least) { |value| value.to_i }

verifier = Aspect::Verifier.new(length_of_at_least: 3)

verifier.verify("12") # => { length_of_at_least: 3 } # Invalid
verifier.verify("123") # => nil                      # Valid

Class Method Summary collapse

Instance Method Summary collapse

Methods included from HasRegistry

register, registered?, registry

Constructor Details

#initialize(&block) ⇒ Check

Returns a new instance of Check.



51
52
53
# File 'lib/aspect/verifier/check.rb', line 51

def initialize(&block)
  self.block = block
end

Class Method Details

.[](name) ⇒ Check

Get a registered ‘Check` instance by it’s name.

Parameters:

  • name (#to_sym)

Returns:



46
47
48
# File 'lib/aspect/verifier/check.rb', line 46

def [](name)
  registry[name.to_sym]
end

Instance Method Details

#block(&block) ⇒ Proc

Get or set the block for the check.

Returns:

  • (Proc)


58
59
60
61
62
# File 'lib/aspect/verifier/check.rb', line 58

def block(&block)
  self.block = block if block_given?

  @block
end

#block=(value) ⇒ Proc

Set the block for the check.

Parameters:

  • value (Proc)

Returns:

  • (Proc)


68
69
70
71
72
73
74
75
76
# File 'lib/aspect/verifier/check.rb', line 68

def block=(value)
  if block_given?
    raise ArgumentError, "block must have 1 block argument" unless value.arity == 1

    @block = value
  end

  @block
end

#call(value, expectation) ⇒ Boolean

Call the block.

Parameters:

  • value (Object)

Returns:

  • (Boolean)


82
83
84
# File 'lib/aspect/verifier/check.rb', line 82

def call(value, expectation)
  !!@block.call(value, expectation) rescue false
end