Class: Cleon::ArGuard

Inherits:
Object
  • Object
show all
Defined in:
lib/cleon/basics/arguard.rb

Overview

The factory for guarding argument values

Examples:

# create a new guard for strings
GuardString = ArGuard.new('string', 'must be String'
  Proc.new{|v| v.is_a?(String)})

# guarding construtor arguments
class Entity
  def initialize(arg)
    @arg = GuardString.(arg)
    # => ArgumentError: :arg must be String
    # @arg = GuardString.(arg, 'name')
    # => ArgumentError: :name must be String
    # @arg = GuardString.(arg, 'name', 'should be String')
    # => ArgumentError: :name should be String
  end
end

Class Method Summary collapse

Class Method Details

.new(name, message, block) ⇒ ArGuard

Parameters:

  • name (String)

    name of the guard

  • meesage (String)

    ArgumentError message

  • block (Proc)

    spec of the guard, must return true or false

Returns:


27
28
29
30
31
32
33
34
# File 'lib/cleon/basics/arguard.rb', line 27

def self.new(name, message, block)
  Class.new do
    define_singleton_method "call" do |val, aname = name, amessage = message|
      return val if block.call(val)
      raise ArgumentError, ":#{aname} #{amessage}", caller[0..-1]
    end
  end
end