Skip to content

Instantly share code, notes, and snippets.

@rx
Created May 1, 2016 19:26
Show Gist options
  • Save rx/2e12ca9c07a1b0c718128872e3a4bd86 to your computer and use it in GitHub Desktop.
Save rx/2e12ca9c07a1b0c718128872e3a4bd86 to your computer and use it in GitHub Desktop.
This is a rework of the example for AutoInject. The example does not run on its own. This one does if you bundle dry-container and dry-auto_inject
require 'dry-container'
require 'dry-auto_inject'
# set up your container
my_container = Dry::Container.new
my_container.register(:data_store, -> { {users:[]} })
my_container.register(:user_repository, -> { my_container[:data_store][:users] })
my_container.register(:persist_user, -> { PersistUser.new })
# set up your auto-injection function
AutoInject = Dry::AutoInject(my_container)
# then simply include it in your class providing which dependencies should be
# injected automatically from the configured container
class PersistUser
include AutoInject[:user_repository]
def call(user)
user_repository << user
end
end
persist_user = my_container[:persist_user]
persist_user.call(name: 'Jane')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment