Skip to content

Instantly share code, notes, and snippets.

@kj
Last active January 24, 2018 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kj/35af5c95c804b760c147ef57da8f0871 to your computer and use it in GitHub Desktop.
Save kj/35af5c95c804b760c147ef57da8f0871 to your computer and use it in GitHub Desktop.

The double splat operator, #to_hash, and dry-auto_inject

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.

Example

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)

Output

{: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"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment