Sha256: d70b9fcafd57828d49817838c794f0fb4a7a558087639a1ff5295bbe0f389a3f

Contents?: true

Size: 940 Bytes

Versions: 2

Compression:

Stored size: 940 Bytes

Contents

#
# Prepares the `:default` option
#
# It must respond to `.call` without arguments
#
module Dry::Initializer::Dispatchers::PrepareDefault
  extend self

  def call(default: nil, optional: nil, **options)
    default = callable! default
    check_arity! default

    { default: default, optional: (optional | default), **options }
  end

  private

  def callable!(default)
    return unless default
    return default if default.respond_to?(:call)
    return callable(default.to_proc) if default.respond_to?(:to_proc)

    invalid!(default)
  end

  def check_arity!(default)
    return unless default

    arity = default.method(:call).arity.to_i
    return unless arity.positive?

    invalid!(default)
  end

  def invalid!(default)
    raise TypeError, "The #{default.inspect} should be" \
                     ' either convertable to proc with no arguments,' \
                     ' or respond to #call without arguments.'
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dry-initializer-3.0.4 lib/dry/initializer/dispatchers/prepare_default.rb
dry-initializer-3.0.3 lib/dry/initializer/dispatchers/prepare_default.rb