Basic parameter validation for dry-initializer?

Hey all,

I am starting to use dry-initializer a lot more to cut back on boilerplate code. It’s awesome!

I am running into a situation where I’d like to perform basic validations for parameters/options passed to the initializer, besides simply enforcing a specific value type. I looked at the doc but couldn’t figure out how to do it.

I’d like to validate two things, for example:

  • value passed should be one from a list of allowed values.
  • value passed should be an array containing only values from a list of allowed values.

The simplest way to do this seems to have a lambda validating the input, but I don’t think it is possible?

What’s the best to achieve something like described above?

Tia

Here’s an example of what I mean:

  class MyClass
    extend Dry::Initializer
    option :foo, validate: proc { |value| %i[a b c].include?(value)) }
    option :bar, type: Dry::Types::Strict::Array, validate: proc { |ary| (ary - %i[foo bar baz]).empty? }
  end

  MyClass.new(foo: :a, bar: [:foo, :bar]) # valid
  MyClass.new(foo: nil, bar: [:fail]) # raises ArgumentError

That’s easily expressable in dry-types

Types = Dry::Types(default: :strict)

Class MyClass
  extend Dry::Initializer
  option :foo, Types::Coercible::Symbol.enum(:a, :b, :c)
  option :bar, Types::Array.of(Types::Coercible::Symbol.enum(:foo, :bar, :baz))
end
1 Like