dry-validation icon indicating copy to clipboard operation
dry-validation copied to clipboard

Injecting dependencies using dry-auto_inject with reserved names

Open flash-gordon opened this issue 2 years ago • 0 comments

Here I'm trying to inject a dependency named config using the default kwargs strategy of dry-auto_inject.

class MyContract < Dry::Validation::Contract
  include Import['config']

  json do
    required(:foo).maybe(:string)
  end

  rule(:foo) do
    key.failure("foo is required") if config.foo_required? && value.nil?
  end
end

config = Object.new.tap do |c|
  def c.foo_required?
    true
  end
end

contract = MyContract.new(config: config)

contract.({ foo: nil })

This results in

/Users/gordon/dev/dry-rb/dry-validation/lib/dry/validation/contract.rb:69:in `block in <class:Contract>': undefined method `macros' for #<Object:0x00000001114c9660> (NoMethodError)

The problem is dry-validation uses config as one of its constructor keywords. dry-auto_inject "guesses" it should pass the dependency down (or up?) to the parent class. This way dry-validation gets the wrong config object. I guess we should rename config to __config__, it should be an easy thing to do. This won't break backward compatibility as far as I can see. Assuming we'll add an alias alias_method :config, :__config__.

flash-gordon avatar Apr 15 '22 07:04 flash-gordon