Class: RSchema::Schemas::Enum

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

Overview

A schema that matches a values in a given set.

Examples:

Rock-Paper-Scissors values

schema = RSchema.define { enum([:rock, :paper, :scissors]) }
schema.valid?(:rock)  #=> true
schema.valid?(:paper) #=> true
schema.valid?(:gun)   #=> false

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(members, subschema) ⇒ Enum


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

def initialize(members, subschema)
  @members = members
  @subschema = subschema
end

Instance Attribute Details

#membersObject (readonly)

Returns the value of attribute members


14
15
16
# File 'lib/rschema/schemas/enum.rb', line 14

def members
  @members
end

#subschemaObject (readonly)

Returns the value of attribute subschema


14
15
16
# File 'lib/rschema/schemas/enum.rb', line 14

def subschema
  @subschema
end

Instance Method Details

#call(value, options) ⇒ Object


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

def call(value, options)
  subresult = subschema.call(value, options)
  if subresult.invalid?
    subresult
  elsif members.include?(subresult.value)
    subresult
  else
    Result.failure(Error.new(
      schema: self,
      value: subresult.value,
      symbolic_name: :not_a_member,
    ))
  end
end

#with_wrapped_subschemas(wrapper) ⇒ Object


36
37
38
# File 'lib/rschema/schemas/enum.rb', line 36

def with_wrapped_subschemas(wrapper)
  self.class.new(members, wrapper.wrap(subschema))
end