Class: RSchema::Schemas::Type

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

Overview

A schema that matches values of a given type (i.e. value.is_a?(type))

Examples:

An Integer schema

schema = RSchema.define { _Integer }
schema.valid?(5) #=> true

A namespaced type

schema = RSchema.define do
  # This will not work:
  # _ActiveWhatever::Thing

  # This will work:
  type(ActiveWhatever::Thing)
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type) ⇒ Type

Returns a new instance of Type


23
24
25
# File 'lib/rschema/schemas/type.rb', line 23

def initialize(type)
  @type = type
end

Instance Attribute Details

#typeObject (readonly)

Returns the value of attribute type


21
22
23
# File 'lib/rschema/schemas/type.rb', line 21

def type
  @type
end

Instance Method Details

#call(value, options) ⇒ Object


27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rschema/schemas/type.rb', line 27

def call(value, options)
  if value.is_a?(@type)
    Result.success(value)
  else
    Result.failure(Error.new(
      schema: self,
      value: value,
      symbolic_name: :wrong_type,
    ))
  end
end

#with_wrapped_subschemas(wrapper) ⇒ Object


39
40
41
# File 'lib/rschema/schemas/type.rb', line 39

def with_wrapped_subschemas(wrapper)
  self
end