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.


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

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

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block


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

def block
  @block
end

#nameObject (readonly)

Returns the value of attribute name


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

def name
  @name
end

Instance Method Details

#call(value, _options) ⇒ Object


23
24
25
26
27
28
29
# File 'lib/rschema/schemas/predicate.rb', line 23

def call(value, _options)
  if block.call(value)
    Result.success(value)
  else
    Result.failure(error(value))
  end
end

#with_wrapped_subschemas(_wrapper) ⇒ Object


31
32
33
# File 'lib/rschema/schemas/predicate.rb', line 31

def with_wrapped_subschemas(_wrapper)
  self
end