Class: Dry::Types::Constructor

Inherits:
Definition show all
Defined in:
lib/dry/types/constructor.rb

Instance Attribute Summary collapse

Attributes inherited from Definition

#options

Attributes included from Options

#options

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Definition

[], #constrained?, #default?, #failure, #name, #primitive?, #result, #success

Methods included from Builder

#constrained, #default, #enum, #maybe, #optional, #safe, #|

Methods included from Options

#meta, #with

Constructor Details

#initialize(type, options = {}, &block) ⇒ Constructor

Returns a new instance of Constructor.



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

def initialize(type, options = {}, &block)
  @type = type
  @fn = options.fetch(:fn, block)
  super
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object (private)



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/dry/types/constructor.rb', line 59

def method_missing(meth, *args, &block)
  if type.respond_to?(meth)
    response = type.__send__(meth, *args, &block)

    if response.kind_of?(Builder)
      self.class.new(response, options)
    else
      response
    end
  else
    super
  end
end

Instance Attribute Details

#fnObject (readonly)

Returns the value of attribute fn.



8
9
10
# File 'lib/dry/types/constructor.rb', line 8

def fn
  @fn
end

#typeObject (readonly)

Returns the value of attribute type.



10
11
12
# File 'lib/dry/types/constructor.rb', line 10

def type
  @type
end

Class Method Details

.new(input, options = {}, &block) ⇒ Object



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

def self.new(input, options = {}, &block)
  type = input.is_a?(Builder) ? input : Definition.new(input)
  super(type, options, &block)
end

Instance Method Details

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



27
28
29
# File 'lib/dry/types/constructor.rb', line 27

def call(input)
  type[fn[input]]
end

#constrained_typeObject



49
50
51
# File 'lib/dry/types/constructor.rb', line 49

def constrained_type
  Constrained::Coercible
end

#constructor(new_fn = nil, **options, &block) ⇒ Object



38
39
40
41
42
43
# File 'lib/dry/types/constructor.rb', line 38

def constructor(new_fn = nil, **options, &block)
  left = new_fn || block
  right = fn

  with(options.merge(fn: -> input { left[right[input]] }))
end

#primitiveObject



23
24
25
# File 'lib/dry/types/constructor.rb', line 23

def primitive
  type.primitive
end

#try(input, &block) ⇒ Object



32
33
34
35
36
# File 'lib/dry/types/constructor.rb', line 32

def try(input, &block)
  type.try(fn[input], &block)
rescue TypeError => e
  failure(input, e.message)
end

#valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/dry/types/constructor.rb', line 45

def valid?(value)
  super && type.valid?(value)
end