Class: Dry::Types::Constrained

Inherits:
Object
  • Object
show all
Includes:
Builder, Decorator
Defined in:
lib/dry/types/constrained.rb,
lib/dry/types/constrained/coercible.rb

Direct Known Subclasses

Coercible

Defined Under Namespace

Classes: Coercible

Instance Attribute Summary collapse

Attributes included from Decorator

#options, #type

Instance Method Summary collapse

Methods included from Builder

#constrained_type, #constructor, #default, #enum, #maybe, #optional, #safe, #|

Methods included from Decorator

#constructor, #respond_to_missing?, #with

Constructor Details

#initialize(type, options) ⇒ Constrained

Returns a new instance of Constrained.



13
14
15
16
# File 'lib/dry/types/constrained.rb', line 13

def initialize(type, options)
  super
  @rule = options.fetch(:rule)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Dry::Types::Decorator

Instance Attribute Details

#ruleObject (readonly)

Returns the value of attribute rule.



11
12
13
# File 'lib/dry/types/constrained.rb', line 11

def rule
  @rule
end

Instance Method Details

#call(input) ⇒ Object Also known as: []



18
19
20
21
22
# File 'lib/dry/types/constrained.rb', line 18

def call(input)
  try(input) do |result|
    raise ConstraintError, result
  end.input
end

#constrained(options) ⇒ Object



39
40
41
# File 'lib/dry/types/constrained.rb', line 39

def constrained(options)
  with(rule: rule & Types.Rule(options))
end

#try(input, &block) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/dry/types/constrained.rb', line 25

def try(input, &block)
  validation = rule.(input)

  if validation.success?
    type.try(input, &block)
  else
    block ? yield(validation) : validation
  end
end

#valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/dry/types/constrained.rb', line 35

def valid?(value)
  rule.(value).success?
end