Class: Xpect::Pred

Inherits:
Object
  • Object
show all
Defined in:
lib/xpect/pred.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pred:, error_msg: nil, default: nil) ⇒ Pred

Returns a new instance of Pred.



7
8
9
10
11
12
13
14
15
# File 'lib/xpect/pred.rb', line 7

def initialize(pred:, error_msg: nil, default: nil)
  unless pred.is_a?(Proc)
    raise "pred must be a Proc"
  end

  @pred = pred
  @error_msg = error_msg
  @default = default
end

Instance Attribute Details

#defaultObject (readonly)

Returns the value of attribute default.



5
6
7
# File 'lib/xpect/pred.rb', line 5

def default
  @default
end

Instance Method Details

#conform!(value:, path: nil) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/xpect/pred.rb', line 17

def conform!(value:, path: nil)
  return @default if @default && value.nil?

  if value.nil?
    raise FailedSpec, "the value at path '#{ path }' is missing"
  end

  unless @pred.call(value)
    error_msg = if @error_msg
                  "'#{ value }' does not meet spec for '#{ path }': '#{ @error_msg }'"
                else
                  "'#{ value }' does not meet spec for '#{ path }'"
                end

    raise FailedSpec, error_msg
  end

  value
end