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

#type

Attributes included from Options

#options

Instance Method Summary collapse

Methods included from Builder

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

Methods included from Decorator

#constructor, #default?, #method_missing, #respond_to_missing?

Methods included from Options

#meta, #with

Constructor Details

#initialize(type, options) ⇒ Constrained

Returns a new instance of Constrained.

Parameters:



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

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

#ruleDry::Logic::Rule (readonly)

Returns:



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

def rule
  @rule
end

Instance Method Details

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

Parameters:

Returns:

Raises:



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

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

#constrained(options) ⇒ Constrained

Parameters:

Returns:

See Also:

  • Logic::Operators#and


59
60
61
# File 'lib/dry/types/constrained.rb', line 59

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

#constrained?true

Returns:



64
65
66
# File 'lib/dry/types/constrained.rb', line 64

def constrained?
  true
end

#decorate?(response) ⇒ Boolean (private)

Parameters:

Returns:



72
73
74
# File 'lib/dry/types/constrained.rb', line 72

def decorate?(response)
  super || response.kind_of?(Constructor)
end

#try(input, &block) {|failure| ... } ⇒ Result

Parameters:

Yield Parameters:

  • failure (Failure)

Yield Returns:

Returns:



37
38
39
40
41
42
43
44
45
46
# File 'lib/dry/types/constrained.rb', line 37

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

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

#valid?(value) ⇒ Boolean

Parameters:

Returns:



50
51
52
# File 'lib/dry/types/constrained.rb', line 50

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