Module: Explicit::Type::Modifiers::Default

Extended by:
Default
Included in:
Default
Defined in:
lib/explicit/type/modifiers/default.rb

Instance Method Summary collapse

Instance Method Details

#apply(default, type) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/explicit/type/modifiers/default.rb', line 6

def apply(default, type)
  Explicit::Type.build(type).tap do |type|
    type.default = default

    original_validate = type.method(:validate)

    type.define_singleton_method(:validate, lambda do |value|
      value =
        if value.nil?
          default.respond_to?(:call) ? default.call : default
        else
          value
        end

      original_validate.(value)
    end)
  end
end