Class: Dry::Data::Constrained

Inherits:
Object
  • Object
show all
Includes:
Decorator, TypeBuilder
Defined in:
lib/dry/data/constrained.rb

Instance Attribute Summary collapse

Attributes included from Decorator

#options, #type

Instance Method Summary collapse

Methods included from TypeBuilder

#default, #enum, #optional, #safe, #|

Methods included from Decorator

#constructor, #respond_to_missing?, #with

Constructor Details

#initialize(type, options) ⇒ Constrained

Returns a new instance of Constrained.



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

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::Data::Decorator

Instance Attribute Details

#ruleObject (readonly)

Returns the value of attribute rule.



10
11
12
# File 'lib/dry/data/constrained.rb', line 10

def rule
  @rule
end

Instance Method Details

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



17
18
19
20
21
22
23
24
25
# File 'lib/dry/data/constrained.rb', line 17

def call(input)
  result = try(input)

  if valid?(result)
    result
  else
    raise ConstraintError, "#{input.inspect} violates constraints"
  end
end

#constrained(options) ⇒ Object



36
37
38
# File 'lib/dry/data/constrained.rb', line 36

def constrained(options)
  with(rule: rule & Data.Rule(primitive, options))
end

#try(input) ⇒ Object



28
29
30
# File 'lib/dry/data/constrained.rb', line 28

def try(input)
  type[input]
end

#valid?(input) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/dry/data/constrained.rb', line 32

def valid?(input)
  super && rule.(input).success?
end