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

Returns a new instance of Enum.


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

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

Instance Attribute Details

#membersObject (readonly)

Returns the value of attribute members


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

def members
  @members
end

#subschemaObject (readonly)

Returns the value of attribute subschema


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

def subschema
  @subschema
end

Instance Method Details

#call(value, options) ⇒ Object


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

def call(value, options)
  subresult = subschema.call(value, options)
  if subresult.invalid?
    subresult
  elsif members.include?(subresult.value)
    subresult
  else
    Result.failure(error(subresult.value))
  end
end

#with_wrapped_subschemas(wrapper) ⇒ Object


33
34
35
# File 'lib/rschema/schemas/enum.rb', line 33

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