Sha256: 7b6ac695842e1915366e53148bef8aec4ac5af7bf29bdd4e7a7760bce8fef868

Contents?: true

Size: 1.11 KB

Versions: 5

Compression:

Stored size: 1.11 KB

Contents

#
# Checks whether an unwrapped type is valid
#
module Dry::Initializer::Dispatchers::CheckType
  extend self

  def call(source:, type: nil, wrap: 0, **options)
    check_if_callable! source, type
    check_arity! source, type, wrap

    { source: source, type: type, wrap: wrap, **options }
  end

  private

  def check_if_callable!(source, type)
    return if type.nil?
    return if type.respond_to?(:call)

    raise ArgumentError,
          "The type of the argument '#{source}' should be callable"
  end

  def check_arity!(_source, type, wrap)
    return if type.nil?
    return if wrap.zero?
    return if type.method(:call).arity.abs == 1

    raise ArgumentError, <<~MESSAGE
      The dry_intitializer supports wrapped types with one argument only.
      You cannot use array types with element coercers having several arguments.

      For example, this definitions are correct:
        option :foo, [proc(&:to_s)]
        option :bar, type: [[]]
        option :baz, ->(a, b) { [a, b] }

      While this is not:
        option :foo, [->(a, b) { [a, b] }]
    MESSAGE
  end
  # rubocop: enable Metrics/MethodLength
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
dry-initializer-3.0.4 lib/dry/initializer/dispatchers/check_type.rb
dry-initializer-3.0.3 lib/dry/initializer/dispatchers/check_type.rb
dry-initializer-3.0.2 lib/dry/initializer/dispatchers/check_type.rb
dry-initializer-3.0.1 lib/dry/initializer/dispatchers/check_type.rb
dry-initializer-3.0.0 lib/dry/initializer/dispatchers/check_type.rb