Class: RSchema::Schemas::Predicate

Inherits:
Object
  • Object
show all
Defined in:
lib/rschema/schemas/predicate.rb

Overview

A schema that uses a given block to determine whether a value is valid

Examples:

A predicate that checks if numbers are odd

schema = RSchema.define do
  predicate('odd'){ |x| x.odd? }
end
schema.valid?(5) #=> true
schema.valid?(6) #=> false

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name = nil, &block) ⇒ Predicate

Returns a new instance of Predicate.



17
18
19
20
# File 'lib/rschema/schemas/predicate.rb', line 17

def initialize(name = nil, &block)
  @block = block
  @name = name
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



15
16
17
# File 'lib/rschema/schemas/predicate.rb', line 15

def block
  @block
end

#nameObject (readonly)

Returns the value of attribute name.



15
16
17
# File 'lib/rschema/schemas/predicate.rb', line 15

def name
  @name
end

Instance Method Details

#call(value, options) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rschema/schemas/predicate.rb', line 22

def call(value, options)
  if block.call(value)
    Result.success(value)
  else
    Result.failure(Error.new(
      schema: self,
      value: value,
      symbolic_name: :false,
      vars: { predicate_name: name }
    ))
  end
end

#with_wrapped_subschemas(wrapper) ⇒ Object



35
36
37
# File 'lib/rschema/schemas/predicate.rb', line 35

def with_wrapped_subschemas(wrapper)
  self
end