Class: Dry::Types::Constrained::Coercible

Inherits:
Dry::Types::Constrained show all
Defined in:
lib/dry/types/constrained/coercible.rb

Overview

Common coercion-related API for constrained types

Instance Attribute Summary

Attributes inherited from Dry::Types::Constrained

#rule

Attributes included from Decorator

#type

Attributes included from Options

#options

Instance Method Summary collapse

Methods inherited from Dry::Types::Constrained

#===, #constrained, #constrained?, #constructor_type, #initialize, #lax, #to_ast

Methods included from Printable

#to_s

Methods included from Builder

#&, #>, #constrained, #constrained_type, #constructor, #constructor_type, #default, #enum, #fallback, #lax, #maybe, #optional, #|

Methods included from Decorator

#constrained?, #default?, #initialize, #respond_to_missing?, #to_proc

Methods included from Options

#initialize, #with

Methods included from Type

#call, #valid?

Constructor Details

This class inherits a constructor from Dry::Types::Constrained

Dynamic Method Handling

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

Instance Method Details

#call_safe(input) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Object)


27
28
29
30
31
32
33
34
35
# File 'lib/dry/types/constrained/coercible.rb', line 27

def call_safe(input)
  coerced = type.call_safe(input) { return yield }

  if rule[coerced]
    coerced
  else
    yield(coerced)
  end
end

#call_unsafe(input) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Object)


13
14
15
16
17
18
19
20
21
22
# File 'lib/dry/types/constrained/coercible.rb', line 13

def call_unsafe(input)
  coerced = type.call_unsafe(input)
  result = rule.(coerced)

  if result.success?
    coerced
  else
    raise ConstraintError.new(result, input)
  end
end

#try(input, &block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/dry/types/constrained/coercible.rb', line 40

def try(input, &block)
  result = type.try(input)

  if result.success?
    validation = rule.(result.input)

    if validation.success?
      result
    else
      failure = failure(result.input, ConstraintError.new(validation, input))
      block ? yield(failure) : failure
    end
  else
    block ? yield(result) : result
  end
end