dependency_manager 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: fdf015a9e6b15915d1fd98278c61812f89bcb10605bedc5cb843762fc17deb11
4
+ data.tar.gz: 4105f52bc2ea4b763dadd7eab398e411df264307f88f86d8558de251dfc5225e
5
+ SHA512:
6
+ metadata.gz: e3bfd2a92306226b7a5c701cececf9547bdfc3211005ede6d452be726f37e3d54aded6f23af1710144caa13f748630baeb682469cb19a147b7ca29cc358dd50a
7
+ data.tar.gz: ac3dff5b1ae91dba7de04656a08a76a2e062dfa69f782ee6c38a747ac0cfb8dd4f358fdcd1a9e6f4e44a722344134aaa04a3983b82c359be6c150bfe31b8dc3d
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at keystonelemur@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in dependency_manager.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,99 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ dependency_manager (0.1.0)
5
+ dry-schema (~> 1.5)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ coderay (1.1.3)
11
+ concurrent-ruby (1.1.8)
12
+ diff-lcs (1.4.4)
13
+ dry-configurable (0.12.1)
14
+ concurrent-ruby (~> 1.0)
15
+ dry-core (~> 0.5, >= 0.5.0)
16
+ dry-container (0.7.2)
17
+ concurrent-ruby (~> 1.0)
18
+ dry-configurable (~> 0.1, >= 0.1.3)
19
+ dry-core (0.5.0)
20
+ concurrent-ruby (~> 1.0)
21
+ dry-inflector (0.2.0)
22
+ dry-initializer (3.0.4)
23
+ dry-logic (1.2.0)
24
+ concurrent-ruby (~> 1.0)
25
+ dry-core (~> 0.5, >= 0.5)
26
+ dry-schema (1.6.2)
27
+ concurrent-ruby (~> 1.0)
28
+ dry-configurable (~> 0.8, >= 0.8.3)
29
+ dry-core (~> 0.5, >= 0.5)
30
+ dry-initializer (~> 3.0)
31
+ dry-logic (~> 1.0)
32
+ dry-types (~> 1.5)
33
+ dry-types (1.5.1)
34
+ concurrent-ruby (~> 1.0)
35
+ dry-container (~> 0.3)
36
+ dry-core (~> 0.5, >= 0.5)
37
+ dry-inflector (~> 0.1, >= 0.1.2)
38
+ dry-logic (~> 1.0, >= 1.0.2)
39
+ ffi (1.15.0)
40
+ formatador (0.2.5)
41
+ guard (2.16.2)
42
+ formatador (>= 0.2.4)
43
+ listen (>= 2.7, < 4.0)
44
+ lumberjack (>= 1.0.12, < 2.0)
45
+ nenv (~> 0.1)
46
+ notiffany (~> 0.0)
47
+ pry (>= 0.9.12)
48
+ shellany (~> 0.0)
49
+ thor (>= 0.18.1)
50
+ guard-compat (1.2.1)
51
+ guard-rspec (4.7.3)
52
+ guard (~> 2.1)
53
+ guard-compat (~> 1.1)
54
+ rspec (>= 2.99.0, < 4.0)
55
+ listen (3.5.1)
56
+ rb-fsevent (~> 0.10, >= 0.10.3)
57
+ rb-inotify (~> 0.9, >= 0.9.10)
58
+ lumberjack (1.2.8)
59
+ method_source (1.0.0)
60
+ nenv (0.3.0)
61
+ notiffany (0.1.3)
62
+ nenv (~> 0.1)
63
+ shellany (~> 0.0)
64
+ pry (0.14.1)
65
+ coderay (~> 1.1)
66
+ method_source (~> 1.0)
67
+ rake (10.5.0)
68
+ rb-fsevent (0.10.4)
69
+ rb-inotify (0.10.1)
70
+ ffi (~> 1.0)
71
+ rspec (3.10.0)
72
+ rspec-core (~> 3.10.0)
73
+ rspec-expectations (~> 3.10.0)
74
+ rspec-mocks (~> 3.10.0)
75
+ rspec-core (3.10.1)
76
+ rspec-support (~> 3.10.0)
77
+ rspec-expectations (3.10.1)
78
+ diff-lcs (>= 1.2.0, < 2.0)
79
+ rspec-support (~> 3.10.0)
80
+ rspec-mocks (3.10.2)
81
+ diff-lcs (>= 1.2.0, < 2.0)
82
+ rspec-support (~> 3.10.0)
83
+ rspec-support (3.10.2)
84
+ shellany (0.0.1)
85
+ thor (1.1.0)
86
+
87
+ PLATFORMS
88
+ ruby
89
+ x86_64-darwin-20
90
+
91
+ DEPENDENCIES
92
+ bundler (~> 2.0)
93
+ dependency_manager!
94
+ guard-rspec (~> 4.7)
95
+ rake (~> 10.0)
96
+ rspec (~> 3.0)
97
+
98
+ BUNDLED WITH
99
+ 2.2.14
data/Guardfile ADDED
@@ -0,0 +1,70 @@
1
+ # A sample Guardfile
2
+ # More info at https://github.com/guard/guard#readme
3
+
4
+ ## Uncomment and set this to only include directories you want to watch
5
+ # directories %w(app lib config test spec features) \
6
+ # .select{|d| Dir.exist?(d) ? d : UI.warning("Directory #{d} does not exist")}
7
+
8
+ ## Note: if you are using the `directories` clause above and you are not
9
+ ## watching the project directory ('.'), then you will want to move
10
+ ## the Guardfile to a watched dir and symlink it back, e.g.
11
+ #
12
+ # $ mkdir config
13
+ # $ mv Guardfile config/
14
+ # $ ln -s config/Guardfile .
15
+ #
16
+ # and, you'll have to watch "config/Guardfile" instead of "Guardfile"
17
+
18
+ # Note: The cmd option is now required due to the increasing number of ways
19
+ # rspec may be run, below are examples of the most common uses.
20
+ # * bundler: 'bundle exec rspec'
21
+ # * bundler binstubs: 'bin/rspec'
22
+ # * spring: 'bin/rspec' (This will use spring if running and you have
23
+ # installed the spring binstubs per the docs)
24
+ # * zeus: 'zeus rspec' (requires the server to be started separately)
25
+ # * 'just' rspec: 'rspec'
26
+
27
+ guard :rspec, cmd: "bundle exec rspec" do
28
+ require "guard/rspec/dsl"
29
+ dsl = Guard::RSpec::Dsl.new(self)
30
+
31
+ # Feel free to open issues for suggestions and improvements
32
+
33
+ # RSpec files
34
+ rspec = dsl.rspec
35
+ watch(rspec.spec_helper) { rspec.spec_dir }
36
+ watch(rspec.spec_support) { rspec.spec_dir }
37
+ watch(rspec.spec_files)
38
+
39
+ # Ruby files
40
+ ruby = dsl.ruby
41
+ dsl.watch_spec_files_for(ruby.lib_files)
42
+
43
+ # Rails files
44
+ rails = dsl.rails(view_extensions: %w(erb haml slim))
45
+ dsl.watch_spec_files_for(rails.app_files)
46
+ dsl.watch_spec_files_for(rails.views)
47
+
48
+ watch(rails.controllers) do |m|
49
+ [
50
+ rspec.spec.call("routing/#{m[1]}_routing"),
51
+ rspec.spec.call("controllers/#{m[1]}_controller"),
52
+ rspec.spec.call("acceptance/#{m[1]}")
53
+ ]
54
+ end
55
+
56
+ # Rails config changes
57
+ watch(rails.spec_helper) { rspec.spec_dir }
58
+ watch(rails.routes) { "#{rspec.spec_dir}/routing" }
59
+ watch(rails.app_controller) { "#{rspec.spec_dir}/controllers" }
60
+
61
+ # Capybara features specs
62
+ watch(rails.view_dirs) { |m| rspec.spec.call("features/#{m[1]}") }
63
+ watch(rails.layouts) { |m| rspec.spec.call("features/#{m[1]}") }
64
+
65
+ # Turnip features and steps
66
+ watch(%r{^spec/acceptance/(.+)\.feature$})
67
+ watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) do |m|
68
+ Dir[File.join("**/#{m[1]}.feature")][0] || "spec/acceptance"
69
+ end
70
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Brandon Weaver
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,566 @@
1
+ # DependencyManager
2
+
3
+ Dependency Manager using Dependency Injection wire together dependencies into a Service Container.
4
+
5
+ This tool may be unnecessary for dependency chains with only a few dependencies, but if you find yourself dealing with 20 or more dependencies you need to wire together this will quickly become very useful.
6
+
7
+ Dependency Manager uses Factories to assemble dependencies, and uses the arguments of `initialize` to figure out what depends on what, and finally what order all the dependencies should be loaded in.
8
+
9
+ Consider this example factory:
10
+
11
+ ```ruby
12
+ class FlagsFactory < DependencyManager::Factory
13
+ # ...
14
+
15
+ def initialize(logger:, timing:, hype_person: nil, **dependencies)
16
+ super(**dependencies)
17
+
18
+ @logger = logger
19
+ @timing = timing
20
+ @hype_person = hype_person
21
+ end
22
+
23
+ # ...
24
+ end
25
+ ```
26
+
27
+ This factory would depend on a `LoggerFactory` and `TimingFactory`, and have an optional dependency on a `HypePerson` factory. The remaining `**dependencies` relate to the base `DependencyManager` factory which we'll get into in a moment.
28
+
29
+ It should be noted that there are no particularly quick starts to using this library. It is suggested to read over the entire Overview and Usage. Quick References will be created soon.
30
+
31
+ ## Overview and Usage
32
+
33
+ DependencyManager uses a few core concepts:
34
+
35
+ * `DependencyTree` - `TSort`-based system for ordering dependencies by what depends on what.
36
+ * `Factory` - Builds dependencies from configuration and validates them.
37
+ * `Resolver` - Resolves dependencies needed for each `Factory`.
38
+ * `Container` - Builds and stores the artifacts of each finished `Factory`.
39
+
40
+ Users will only directly interact with the `Factory` and the `Container`, while `DependencyTree` and `Resolver` will help wire everything together behind the scenes. We'll be focusing on the two public interfaces.
41
+
42
+ ### Factories
43
+
44
+ A `Factory` seeks to fulfill a few goals:
45
+
46
+ * **Filtering** - A `Factory` may be disabled, causing it to not build.
47
+ * **Configure** - Defines and extracts configuration for dependencies.
48
+ * **Validate** - Validates that configuration using `Dry::Schema`.
49
+ * **Loading** - Loads external dependencies like gems via `require`.
50
+ * **Dependency Chains** - Finds dependencies necessary to "build" a factory.
51
+ * **Build** - Builds the dependency based on the above content.
52
+
53
+ #### Factory Filtering
54
+
55
+ Factories can be enabled or disabled through the `enabled?` method, which defaults to `false` in the `Factory` class which children inherit from:
56
+
57
+ ```ruby
58
+ class MyFactory > DependencyManager::Factory
59
+ # ...
60
+
61
+ def enabled?
62
+ configuration[:enabled] == true
63
+ end
64
+
65
+ # ...
66
+ end
67
+ ```
68
+
69
+ Just defining this method, however, will not do much unless you remember to put it in your build step:
70
+
71
+ ```ruby
72
+ class MyFactory > DependencyManager::Factory
73
+ # ...
74
+
75
+ def build
76
+ return unless enabled?
77
+
78
+ # ...
79
+ end
80
+
81
+ def enabled?
82
+ configuration[:enabled] == true
83
+ end
84
+
85
+ # ...
86
+ end
87
+ ```
88
+
89
+ ...which will cause it to not be injected into downstream `Factory` builds.
90
+
91
+ #### Factory Configuration
92
+
93
+ Factories are configured via an injected `Hash` from the `Container`, and a user determined `app_context`:
94
+
95
+ ```ruby
96
+ # /lib/dependency_manager/factory.rb
97
+ def initialize(app_context: nil, factory_config:)
98
+ @app_context = app_context
99
+ @factory_config = factory_config
100
+ end
101
+ ```
102
+
103
+ The application context is typically a class containing information like environment, name, and other meta-information. This is defaulted to `nil` to represent an optional dependency.
104
+
105
+ The `factory_config` is derived from the name of the `Factory`:
106
+
107
+ ```ruby
108
+ # /lib/dependency_manager/container.rb
109
+ private def get_config(klass)
110
+ @configuration.fetch(klass.dependency_name, {})
111
+ end
112
+ ```
113
+
114
+ ...which is automatically provided from the `Factory`s class name. For instance, `LoggerFactory` would have a dependency name of `logger`, and would feed the `logger` values from the following configuration passed to a container:
115
+
116
+ ```ruby
117
+ # /spec/dependency_manager/container_spec.rb
118
+ {
119
+ logger: { enabled: true, level: :info },
120
+ flags: { enabled: true, default_values: { a: 1, b: 2, c: 3 } },
121
+ timing: { enabled: true },
122
+ hype_person: { enabled: true }
123
+ }
124
+ ```
125
+
126
+ In your own `Factory`s there are two configuration methods to keep in mind: `configuration` and `default_configuration`:
127
+
128
+ ```ruby
129
+ # Inline definition
130
+
131
+ # Config stanza:
132
+ # { a: 3, b: 4 }
133
+
134
+ class MyFactory < DependencyManager::Factory
135
+ # Depends on logger, forwards `app_context` and `configuration` on to the parent class
136
+ def initialize(logger:, **dependencies)
137
+ super(**dependencies)
138
+ @logger = logger
139
+ end
140
+
141
+ # Would return: { a: 3, b: 4, c: 3 }
142
+ def configuration
143
+ # Default implementation, use `super()` here to get this config
144
+ # if you want to do more configuration. Caching is used by default as well.
145
+ @configuration ||= deep_merge(default_configuration, @factory_config)
146
+ end
147
+
148
+ # Reasonable defaults for the class, defaulting to `{}` unless specified
149
+ def default_configuration
150
+ { a: 1, b: 2, c: 3 }
151
+ end
152
+ end
153
+ ```
154
+
155
+ Configurations are typically used in the build phase of a `Factory`.
156
+
157
+ As with other methods it's not necessary unless you need it, and `build` will not automiatically call it.
158
+
159
+ #### Factory Validation
160
+
161
+ An optional, but recommended step, to validate configurations:
162
+
163
+ ```ruby
164
+ # /spec/support/dependency_factories/flags_factory.rb
165
+ class FlagsFactory < DependencyManager::Factory
166
+ validate_with do
167
+ required(:enabled).filled(:bool)
168
+ required(:default_values).hash
169
+ end
170
+
171
+ # ...
172
+ end
173
+ ```
174
+
175
+ This will validate `configuration` by using [`Dry::Schema`](https://dry-rb.org/gems/dry-validation/1.6/) validations via the `validate!` (error raising) and `validate` (result returning) methods.
176
+
177
+ It's recommended to run this in the `build` step of your `Factory` right after checking if it's enabled:
178
+
179
+ ```ruby
180
+ # /spec/support/dependency_factories/flags_factory.rb
181
+ class FlagsFactory < DependencyManager::Factory
182
+ validate_with do
183
+ required(:enabled).filled(:bool)
184
+ required(:default_values).hash
185
+ end
186
+
187
+ # ...
188
+
189
+ def build
190
+ return unless enabled?
191
+
192
+ validate!
193
+
194
+ # ...
195
+ end
196
+
197
+ # ...
198
+ end
199
+ ```
200
+
201
+ As with other methods it's not necessary unless you need it, and `build` will not automiatically call it.
202
+
203
+ #### Factory Loading
204
+
205
+ Some `Factory`s, if not most, are created to load gems that you don't own into your Service Container ecosystem. `load_requirements` is how `DependencyManager` handles that issue:
206
+
207
+ ```ruby
208
+ # /spec/support/dependency_factories/flags_factory.rb
209
+ class FlagsFactory < DependencyManager::Factory
210
+ # ...
211
+
212
+ def build
213
+ return unless enabled?
214
+
215
+ validate!
216
+
217
+ load_dependencies
218
+
219
+ # ...
220
+ end
221
+
222
+ def load_dependencies
223
+ require 'flags'
224
+ end
225
+
226
+ # ...
227
+ end
228
+ ```
229
+
230
+ As with other methods it's not necessary unless you need it, and `build` will not automiatically call it.
231
+
232
+ #### Factory Dependency Chains
233
+
234
+ Dependency chains are the main reason this library exists. In a Service Container dependencies rely on eachother, often times in hard to manage orders. `DependencyManager` solves this using the arguments to the `initialize` function on each `Factory` to find dependencies:
235
+
236
+ ```ruby
237
+ def initialize(logger:, other:, optional: nil)
238
+ ```
239
+
240
+ In this case there are required dependencies on `:logger` and `:other`, but an optional dependency on `:optional`. These work via required kwargs and optional kwargs, and `nil` isn't the only value that can be used there, in fact more sane defaults are a better idea where possible.
241
+
242
+ These names correspond to, and require the presence of factories named `LoggerFactory`, `OtherFactory`, and `OptionalFactory`. Without them the program will crash and warn you of this:
243
+
244
+ ```ruby
245
+ # spec/dependency_manager/factory_spec.rb > .get > When the factory does not exist
246
+ "Tried to get non-existant Factory. Did you remember to define it?: InvalidFactory"
247
+ ```
248
+
249
+ Missing resources in general will attempt to raise informative errors to let you know what might have gone wrong.
250
+
251
+ #### Factory Builds
252
+
253
+ The final step of a factory is to actually build it and get the dependency back out the other side, and all together it'll look a bit something like this:
254
+
255
+ ```ruby
256
+ # /spec/dependency_manager/container_spec.rb
257
+ #
258
+ # Flag configuration stanza:
259
+ { enabled: true, default_values: { a: 1, b: 2, c: 3 } },
260
+
261
+ # /spec/support/dependency_factories/flags_factory.rb
262
+ class FlagsFactory < DependencyManager::Factory
263
+ validate_with do
264
+ required(:enabled).filled(:bool)
265
+ required(:default_values).hash
266
+ end
267
+
268
+ def initialize(logger:, timing:, hype_person: nil, **dependencies)
269
+ super(**dependencies)
270
+
271
+ @logger = logger
272
+ @timing = timing
273
+ @hype_person = hype_person
274
+ end
275
+
276
+ def build
277
+ return unless enabled?
278
+
279
+ validate!
280
+
281
+ load_requirements
282
+
283
+ Flags.new(
284
+ logger: @logger,
285
+ timing: @timing,
286
+ default_values: configuration[:default_values],
287
+ hype_person: @hype_person
288
+ )
289
+ end
290
+
291
+ def load_requirements
292
+ require 'flags'
293
+ end
294
+
295
+ def enabled?
296
+ configuration[:enabled] == true
297
+ end
298
+ end
299
+ ```
300
+
301
+ In general the order for a `build` function should be:
302
+
303
+ * Is it on?
304
+ * Is it valid?
305
+ * What do we need to load to make it work?
306
+ * Get configuration ready
307
+ * Build it!
308
+
309
+ This factory has no `configuration` step defined, but uses the automatically built `configuration` to get `:default_values`.
310
+
311
+ Once built by the `Container` it will be registered and fed to other dependencies executing later that require what it produces, which brings us to `Container` next.
312
+
313
+ ### Containers
314
+
315
+ A `Container` is what brings all the `Factory`s together to produce the dependencies you need to run your application.
316
+
317
+ It aims to do a few things:
318
+
319
+ * **Capture Configuration** - `Container` takes pre-read configuration in the format `Hash[Symbol, Any]`
320
+ * **Load Factories** - Load all the `Factory`s
321
+ * **Load Dependency Tree** - Call out to `DependencyTree` and find out what needs to be built
322
+ * **Order Dependencies** - Based on dependencies, use `tsort` to order dependencies from `DependencyTree`.
323
+ * **Resolve Dependencies** - Resolve requirements from `Factory` based on what's already been built, if any are required.
324
+ * **Build Factory** - Build the `Factory` and wire it back into dependencies for downstream `Factory`s to potentially use.
325
+ * **Present Dependencies** - Once they're done, give back dependencies to use how you see fit.
326
+
327
+ #### Container Configuration
328
+
329
+ `Container` will not load configuration, but instead takes it directly in the form of a `Hash[Symbol, Any]`:
330
+
331
+ ```ruby
332
+ # Modified from: /spec/dependency_manager/container_spec.rb
333
+
334
+ AppContext = Struct.new(:name, :env)
335
+
336
+ container = DependencyManager::Container.new(
337
+ app_context: AppContext.new('README', 'test'),
338
+ configuration: {
339
+ logger: { enabled: true, level: :info },
340
+ flags: { enabled: true, default_values: { a: 1, b: 2, c: 3 } },
341
+ timing: { enabled: true },
342
+ hype_person: { enabled: true }
343
+ },
344
+ factories: DependencyManager::Factory.factories
345
+ )
346
+
347
+ container.build
348
+
349
+ container.fetch(:logger)
350
+ # => instance_of Logger
351
+ ```
352
+
353
+ Typically this would come from a `YAML` or `JSON` file, but can be manually entered as well.
354
+
355
+ An `AppContext` can be any class, but is typically useful for changing behavior based on application-level configuration like what environment the script is currently running on and using different configs if it's in sandbox vs production. This option is not necessary, but recommended for more complicated applications.
356
+
357
+ #### Container Loading Factories
358
+
359
+ The `factories` option for creating a new `Container` defaults to `Factory.factories`, which contains all classes inheriting from `DependencyManager::Factory`. If this behavior is not wanted an `Array` of `Factory`s can be passed in instead:
360
+
361
+ ```ruby
362
+ # Modified from: /spec/dependency_manager/container_spec.rb
363
+ factories: DependencyManager::Factory.factories
364
+
365
+ # ...or manually
366
+ factories: [LoggerFactory, FlagsFactory, HypePersonFactory]
367
+ ```
368
+
369
+ When using the manual route one can also use `register` to add a new `Factory` before the `Container` is built:
370
+
371
+ ```ruby
372
+ container = DependencyManager::Container.new(...)
373
+ container.register(HypePersonFactory)
374
+ ```
375
+
376
+ ...but as this uses a `Set` behind the scenes it will not allow a `Factory` to be loaded more than once.
377
+
378
+ #### Container Loading Dependency Tree
379
+
380
+ `Container` uses `DependencyTree` to figure out what depends on what. Using a basic example:
381
+
382
+ ```ruby
383
+ # /spec/dependency_manager/dependency_tree_spec.rb
384
+ tree = DependencyManager::DependencyTree.new(
385
+ a: [:b, :c],
386
+ b: [:c],
387
+ c: []
388
+ )
389
+ ```
390
+
391
+ `a` depends on `b` and `c`, `b` depends on `c`, and `c` depends on nothing. Remembering back above, `Factory`s implement a method for finding what other `Factory`s they depend on using the arguments to `initialize` via `factory_dependencies`:
392
+
393
+ ```ruby
394
+ # /lib/dependency_manager/factory.rb > Singleton methods
395
+
396
+ def parameters
397
+ instance_method(:initialize).parameters
398
+ end
399
+
400
+ def dependencies
401
+ dependencies = parameters
402
+ .select { |type, _name| KEYWORD_ARGS.include?(type) }
403
+ .map(&:last)
404
+
405
+ dependencies - CONTEXT_DEPENDENCIES
406
+ end
407
+
408
+ def factory_dependencies
409
+ dependencies.map { |d| "#{d}_factory".to_sym }
410
+ end
411
+ ```
412
+
413
+ So our above hypothetical `initialize` method:
414
+
415
+ ```ruby
416
+ def initialize(logger:, other:, optional: nil)
417
+ ```
418
+
419
+ ...would give us the following dependency chain:
420
+
421
+ ```ruby
422
+ [:logger_factory, :other_factory, :optional_factory]
423
+ ```
424
+
425
+ It also has additional methods of `required_dependencies` and `optional_dependencies` to figude out what's actually needed to build it successfully. All of this comes for free based on arguments to `initialize` of each `Factory`.
426
+
427
+ #### Container Ordering Dependencies
428
+
429
+ Given these `TSort`, which is included in `DependencyTree`, can figure out what order to load dependencies in. Taking a look at our above:
430
+
431
+ ```ruby
432
+ # /spec/dependency_manager/dependency_tree_spec.rb
433
+ tree = DependencyManager::DependencyTree.new(
434
+ a: [:b, :c],
435
+ b: [:c],
436
+ c: []
437
+ )
438
+
439
+ tree.tsort
440
+ # => [:c, :b, :a]
441
+ ```
442
+
443
+ It would run `c` then `b` then `a`, which makes sense as `c` has no other dependencies.
444
+
445
+ `TSort` is also kind enough to keep us from creating cycles by accident:
446
+
447
+ ```ruby
448
+ # /spec/dependency_manager/dependency_tree_spec.rb
449
+ tree = DependencyManager::DependencyTree.new(
450
+ a: [:b, :c],
451
+ b: [:c],
452
+ c: [:b] # LOOP
453
+ )
454
+
455
+ tree.tsort
456
+ # raises TSort::Cyclic
457
+ ```
458
+
459
+ #### Container Resolving Dependencies
460
+
461
+ ```ruby
462
+ # /lib/dependency_manager/container.rb
463
+ resolved_dependencies = Resolver.new(
464
+ factory: factory,
465
+ loaded_dependencies: dependencies
466
+ ).resolve
467
+ ```
468
+
469
+ As each dependency is built it will look into the already built dependencies for dependencies it needs. If `c` is built first, `dependencies` will already have a reference to it for `b` when it comes up to be built, and so forth for `a`.
470
+
471
+ `/spec/dependency_manager/resolver_spec.rb` contains examples of this behavior, but for now know that it relies on order to cascade dependencies where they need to go when they need to be there.
472
+
473
+ #### Container Building Dependencies
474
+
475
+ Once we have the dependencies we can inject hte rest of the information we need, and we now have a factory ready to be built:
476
+
477
+ ```ruby
478
+ # /lib/dependency_manager/container.rb
479
+ factory_instance = factory.new(
480
+ app_context: @app_context,
481
+ factory_config: get_config(factory),
482
+ **resolved_dependencies
483
+ )
484
+ ```
485
+
486
+ ...once ready we turn around and build it:
487
+
488
+ ```ruby
489
+ # /lib/dependency_manager/container.rb
490
+ @dependencies[factory.dependency_name] = factory_instance.build
491
+ ```
492
+
493
+ `Factory`s have `dependency_name` which gives back a snake-cased version of just the dependency name, such that `LoggerFactory` becomes `logger`, which is what other `Factory`s expect. We map that name to the produced artifact, and that artifact is now available to all `Factory`s that build after it.
494
+
495
+ This is the reason for `TSort` is to figure out what that order is. Note this may not be necessary in cases where your dependencies do not have to be actively loaded, and something like `Dry::Container` may be a better idea in those cases.
496
+
497
+ #### Container Presenting Dependencies
498
+
499
+ Once that's done all of the dependencies have been created and you can get them out in a few ways:
500
+
501
+ ```ruby
502
+ # Modified from: /spec/dependency_manager/container_spec.rb
503
+
504
+ AppContext = Struct.new(:name, :env)
505
+
506
+ container = DependencyManager::Container.new(
507
+ app_context: AppContext.new('README', 'test'),
508
+ configuration: {
509
+ logger: { enabled: true, level: :info },
510
+ flags: { enabled: true, default_values: { a: 1, b: 2, c: 3 } },
511
+ timing: { enabled: true },
512
+ hype_person: { enabled: true }
513
+ },
514
+ factories: DependencyManager::Factory.factories
515
+ )
516
+
517
+ container.build
518
+ # All dependencies returned here too, but prefer to use the next two methods
519
+
520
+ container.fetch(:logger)
521
+ # => instance_of Logger
522
+
523
+ container.to_h
524
+ # {
525
+ # logger: instance_of Logger,
526
+ # flags: instance_of Flags,
527
+ # timing: instance_of Timing,
528
+ # hype_person: instance_of HypePerson
529
+ # }
530
+ ```
531
+
532
+ ...and with that you now have a `Container` to work with, whether that be tying into Rails or whatever other framework you're needing to.
533
+
534
+ ## Installation
535
+
536
+ Add this line to your application's Gemfile:
537
+
538
+ ```ruby
539
+ gem 'dependency_manager'
540
+ ```
541
+
542
+ And then execute:
543
+
544
+ $ bundle
545
+
546
+ Or install it yourself as:
547
+
548
+ $ gem install dependency_manager
549
+
550
+ ## Development
551
+
552
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
553
+
554
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
555
+
556
+ ## Contributing
557
+
558
+ Bug reports and pull requests are welcome on GitHub at https://github.com/baweaver/dependency_manager. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
559
+
560
+ ## License
561
+
562
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
563
+
564
+ ## Code of Conduct
565
+
566
+ Everyone interacting in the DependencyManager project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/dependency_manager/blob/master/CODE_OF_CONDUCT.md).