I'm having some trouble with the dry-auto_inject
Ruby gem when an object that responds to #to_hash
(such as Hanami::Entity
in my case) is passed as the last argument to .new
. When this happens, the generated .new
method implicitly converts the object to a hash (because #to_h
is for explicit conversion and #to_hash
is for implicit conversion, so the double splat operator converts the object), and when passed to #initialize
, the injected dependencies and the converted hash are passed altogether as a hash as the first argument.
require 'dry-container'
require 'dry-auto_inject'
C = Dry::Container.new
A = Dry::AutoInject(C)
C.register(:example1, 1)
class WithToHash
def to_hash
{oops: 'I am implicitly converted by double splat operator'}
end
end
class WithoutToHash
end
class Example
include A[:example1]
def initialize(arg, **kwargs)
super(**kwargs)
@arg = arg
end
attr_reader :arg
def call
p arg
p example1
end
end
def direct_example(arg, **kwargs)
p arg
p kwargs
end
Example.new(WithToHash.new).()
Example.new(WithoutToHash.new).()
direct_example(WithToHash.new)
direct_example(WithToHash.new, WithToHash.new)
{:oops=>"I am implicitly converted by double splat operator", :example1=>1}
nil
#<WithoutToHash:0x000055feadc69588>
1
#<WithToHash:0x000055feadc691c8>
{}
#<WithToHash:0x000055feadc69060>
{:oops=>"I am implicitly converted by double splat operator"}