class RSchema::Schemas::Predicate

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

@example 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

Attributes

block[R]
name[R]

Public Class Methods

new(name = nil, &block) click to toggle source
# File lib/rschema/schemas/predicate.rb, line 18
def initialize(name = nil, &block)
  @block = block
  @name = name
end

Public Instance Methods

call(value, _options) click to toggle source
# 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) click to toggle source
# File lib/rschema/schemas/predicate.rb, line 31
def with_wrapped_subschemas(_wrapper)
  self
end

Private Instance Methods

error(value) click to toggle source
# File lib/rschema/schemas/predicate.rb, line 37
def error(value)
  Error.new(
    schema: self,
    value: value,
    symbolic_name: :false,
    vars: { predicate_name: name },
  )
end