-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
auto_inject.rb
64 lines (60 loc) · 1.71 KB
/
auto_inject.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# frozen_string_literal: true
require "zeitwerk"
require "dry/core"
module Dry
module AutoInject
def self.loader
@loader ||= Zeitwerk::Loader.new.tap do |loader|
root = File.expand_path("..", __dir__)
loader.tag = "dry-auto_inject"
loader.inflector = Zeitwerk::GemInflector.new("#{root}/dry-auto_inject.rb")
loader.push_dir(root)
loader.ignore(
"#{root}/dry-auto_inject.rb",
"#{root}/dry/auto_inject/version.rb"
)
end
end
loader.setup
end
# Configure an auto-injection module
#
# @example
# module MyApp
# # set up your container
# container = Dry::Core::Container.new
#
# container.register(:data_store, -> { DataStore.new })
# container.register(:user_repository, -> { container[:data_store][:users] })
# container.register(:persist_user, -> { PersistUser.new })
#
# # set up your auto-injection function
# AutoInject = Dry::AutoInject(container)
#
# # define your injection function
# def self.Inject(*keys)
# AutoInject[*keys]
# end
# end
#
# # then simply include it in your class providing which dependencies should be
# # injected automatically from the configured container
# class PersistUser
# include MyApp::Inject(:user_repository)
#
# def call(user)
# user_repository << user
# end
# end
#
# persist_user = container[:persist_user]
#
# persist_user.call(name: 'Jane')
#
# @return [Proc] calling the returned proc builds an auto-injection module
#
# @api public
def self.AutoInject(container, options = {})
AutoInject::Builder.new(container, options)
end
end