{"id":13878864,"url":"https://github.com/baweaver/dependency_manager","last_synced_at":"2025-07-16T14:33:07.104Z","repository":{"id":62557002,"uuid":"363877780","full_name":"baweaver/dependency_manager","owner":"baweaver","description":"Dependency Management prototype","archived":false,"fork":false,"pushed_at":"2021-05-06T21:34:52.000Z","size":45,"stargazers_count":13,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2024-08-11T00:27:34.421Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/baweaver.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-05-03T09:23:45.000Z","updated_at":"2024-03-25T09:51:48.000Z","dependencies_parsed_at":"2022-11-03T06:15:28.756Z","dependency_job_id":null,"html_url":"https://github.com/baweaver/dependency_manager","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baweaver%2Fdependency_manager","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baweaver%2Fdependency_manager/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baweaver%2Fdependency_manager/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baweaver%2Fdependency_manager/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/baweaver","download_url":"https://codeload.github.com/baweaver/dependency_manager/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":226138849,"owners_count":17579496,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-06T08:02:02.515Z","updated_at":"2024-11-24T07:31:21.890Z","avatar_url":"https://github.com/baweaver.png","language":"Ruby","readme":"# DependencyManager\n\nDependency Manager using Dependency Injection wire together dependencies into a Service Container.\n\nThis 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.\n\nDependency 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.\n\nConsider this example factory:\n\n```ruby\nclass FlagsFactory \u003c DependencyManager::Factory\n  # ...\n\n  def initialize(logger:, timing:, hype_person: nil, **dependencies)\n    super(**dependencies)\n\n    @logger = logger\n    @timing = timing\n    @hype_person = hype_person\n  end\n\n  # ...\nend\n```\n\nThis 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.\n\nIt 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.\n\n## Overview and Usage\n\nDependencyManager uses a few core concepts:\n\n* `DependencyTree` - `TSort`-based system for ordering dependencies by what depends on what.\n* `Factory` - Builds dependencies from configuration and validates them.\n* `Resolver` - Resolves dependencies needed for each `Factory`.\n* `Container` - Builds and stores the artifacts of each finished `Factory`.\n\nUsers 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.\n\n### Factories\n\nA `Factory` seeks to fulfill a few goals:\n\n* **Filtering** - A `Factory` may be disabled, causing it to not build.\n* **Configure** - Defines and extracts configuration for dependencies.\n* **Validate** - Validates that configuration using `Dry::Schema`.\n* **Loading** - Loads external dependencies like gems via `require`.\n* **Dependency Chains** - Finds dependencies necessary to \"build\" a factory.\n* **Build** - Builds the dependency based on the above content.\n\n#### Factory Filtering\n\nFactories can be enabled or disabled through the `enabled?` method, which defaults to `false` in the `Factory` class which children inherit from:\n\n```ruby\nclass MyFactory \u003c DependencyManager::Factory\n  # ...\n\n  def enabled?\n    configuration[:enabled] == true\n  end\n\n  # ...\nend\n```\n\nJust defining this method, however, will not do much unless you remember to put it in your build step:\n\n```ruby\nclass MyFactory \u003c DependencyManager::Factory\n  # ...\n\n  def build\n    return unless enabled?\n\n    # ...\n  end\n\n  def enabled?\n    configuration[:enabled] == true\n  end\n\n  # ...\nend\n```\n\n...which will cause it to not be injected into downstream `Factory` builds.\n\n#### Factory Configuration\n\nFactories are configured via an injected `Hash` from the `Container`, and a user determined `app_context`:\n\n```ruby\n# /lib/dependency_manager/factory.rb\ndef initialize(app_context: nil, factory_config:)\n  @app_context = app_context\n  @factory_config = factory_config\nend\n```\n\nThe 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.\n\nThe `factory_config` is derived from the name of the `Factory`:\n\n```ruby\n# /lib/dependency_manager/container.rb\nprivate def get_config(klass)\n  @configuration.fetch(klass.dependency_name, {})\nend\n```\n\n...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:\n\n```ruby\n# /spec/dependency_manager/container_spec.rb\n{\n  logger:      { enabled: true, level: :info },\n  flags:       { enabled: true, default_values: { a: 1, b: 2, c: 3 } },\n  timing:      { enabled: true },\n  hype_person: { enabled: true }\n}\n```\n\nIn your own `Factory`s there are two configuration methods to keep in mind: `configuration` and `default_configuration`:\n\n```ruby\n# Inline definition\n\n# Config stanza:\n#   { a: 3, b: 4 }\n\nclass MyFactory \u003c DependencyManager::Factory\n  # Depends on logger, forwards `app_context` and `configuration` on to the parent class\n  def initialize(logger:, **dependencies)\n    super(**dependencies)\n    @logger = logger\n  end\n\n  # Would return: { a: 3, b: 4, c: 3 }\n  def configuration\n    # Default implementation, use `super()` here to get this config\n    # if you want to do more configuration. Caching is used by default as well.\n    @configuration ||= deep_merge(default_configuration, @factory_config)\n  end\n\n  # Reasonable defaults for the class, defaulting to `{}` unless specified\n  def default_configuration\n    { a: 1, b: 2, c: 3 }\n  end\nend\n```\n\nConfigurations are typically used in the build phase of a `Factory`.\n\nAs with other methods it's not necessary unless you need it, and `build` will not automiatically call it.\n\n#### Factory Validation\n\nAn optional, but recommended step, to validate configurations:\n\n```ruby\n# /spec/support/dependency_factories/flags_factory.rb\nclass FlagsFactory \u003c DependencyManager::Factory\n  validate_with do\n    required(:enabled).filled(:bool)\n    required(:default_values).hash\n  end\n\n  # ...\nend\n```\n\nThis 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.\n\nIt's recommended to run this in the `build` step of your `Factory` right after checking if it's enabled:\n\n```ruby\n# /spec/support/dependency_factories/flags_factory.rb\nclass FlagsFactory \u003c DependencyManager::Factory\n  validate_with do\n    required(:enabled).filled(:bool)\n    required(:default_values).hash\n  end\n\n  # ...\n\n  def build\n    return unless enabled?\n\n    validate!\n\n    # ...\n  end\n\n  # ...\nend\n```\n\nAs with other methods it's not necessary unless you need it, and `build` will not automiatically call it.\n\n#### Factory Loading\n\nSome `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:\n\n```ruby\n# /spec/support/dependency_factories/flags_factory.rb\nclass FlagsFactory \u003c DependencyManager::Factory\n  # ...\n\n  def build\n    return unless enabled?\n\n    validate!\n\n    load_dependencies\n\n    # ...\n  end\n\n  def load_dependencies\n    require 'flags'\n  end\n\n  # ...\nend\n```\n\nAs with other methods it's not necessary unless you need it, and `build` will not automiatically call it.\n\n#### Factory Dependency Chains\n\nDependency chains are the main reason this library exists. In a Service Container dependencies rely on each other, often times in hard to manage orders. `DependencyManager` solves this using the arguments to the `initialize` function on each `Factory` to find dependencies:\n\n```ruby\ndef initialize(logger:, other:, optional: nil)\n```\n\nIn 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.\n\nThese 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:\n\n```ruby\n# spec/dependency_manager/factory_spec.rb \u003e .get \u003e When the factory does not exist\n\"Tried to get non-existant Factory. Did you remember to define it?: InvalidFactory\"\n```\n\nMissing resources in general will attempt to raise informative errors to let you know what might have gone wrong.\n\n#### Factory Builds\n\nThe 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:\n\n```ruby\n# /spec/dependency_manager/container_spec.rb\n#\n# Flag configuration stanza:\n{ enabled: true, default_values: { a: 1, b: 2, c: 3 } },\n\n# /spec/support/dependency_factories/flags_factory.rb\nclass FlagsFactory \u003c DependencyManager::Factory\n  validate_with do\n    required(:enabled).filled(:bool)\n    required(:default_values).hash\n  end\n\n  def initialize(logger:, timing:, hype_person: nil, **dependencies)\n    super(**dependencies)\n\n    @logger = logger\n    @timing = timing\n    @hype_person = hype_person\n  end\n\n  def build\n    return unless enabled?\n\n    validate!\n\n    load_requirements\n\n    Flags.new(\n      logger: @logger,\n      timing: @timing,\n      default_values: configuration[:default_values],\n      hype_person: @hype_person\n    )\n  end\n\n  def load_requirements\n    require 'flags'\n  end\n\n  def enabled?\n    configuration[:enabled] == true\n  end\nend\n```\n\nIn general the order for a `build` function should be:\n\n* Is it on?\n* Is it valid?\n* What do we need to load to make it work?\n* Get configuration ready\n* Build it!\n\nThis factory has no `configuration` step defined, but uses the automatically built `configuration` to get `:default_values`.\n\nOnce 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.\n\n### Containers\n\nA `Container` is what brings all the `Factory`s together to produce the dependencies you need to run your application.\n\nIt aims to do a few things:\n\n* **Capture Configuration** - `Container` takes pre-read configuration in the format `Hash[Symbol, Any]`\n* **Load Factories** - Load all the `Factory`s\n* **Load Dependency Tree** - Call out to `DependencyTree` and find out what needs to be built\n* **Order Dependencies** - Based on dependencies, use `tsort` to order dependencies from `DependencyTree`.\n* **Resolve Dependencies** - Resolve requirements from `Factory` based on what's already been built, if any are required.\n* **Build Factory** - Build the `Factory` and wire it back into dependencies for downstream `Factory`s to potentially use.\n* **Present Dependencies** - Once they're done, give back dependencies to use how you see fit.\n\n#### Container Configuration\n\n`Container` will not load configuration, but instead takes it directly in the form of a `Hash[Symbol, Any]`:\n\n```ruby\n# Modified from: /spec/dependency_manager/container_spec.rb\n\nAppContext = Struct.new(:name, :env)\n\ncontainer = DependencyManager::Container.new(\n  app_context:   AppContext.new('README', 'test'),\n  configuration: {\n    logger:      { enabled: true, level: :info },\n    flags:       { enabled: true, default_values: { a: 1, b: 2, c: 3 } },\n    timing:      { enabled: true },\n    hype_person: { enabled: true }\n  },\n  factories: DependencyManager::Factory.factories\n)\n\ncontainer.build\n\ncontainer.fetch(:logger)\n# =\u003e instance_of Logger\n```\n\nTypically this would come from a `YAML` or `JSON` file, but can be manually entered as well.\n\nAn `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.\n\n#### Container Loading Factories\n\nThe `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:\n\n```ruby\n# Modified from: /spec/dependency_manager/container_spec.rb\nfactories: DependencyManager::Factory.factories\n\n# ...or manually\nfactories: [LoggerFactory, FlagsFactory, HypePersonFactory]\n```\n\nWhen using the manual route one can also use `register` to add a new `Factory` before the `Container` is built:\n\n```ruby\ncontainer = DependencyManager::Container.new(...)\ncontainer.register(HypePersonFactory)\n```\n\n...but as this uses a `Set` behind the scenes it will not allow a `Factory` to be loaded more than once.\n\n#### Container Loading Dependency Tree\n\n`Container` uses `DependencyTree` to figure out what depends on what. Using a basic example:\n\n```ruby\n# /spec/dependency_manager/dependency_tree_spec.rb\ntree = DependencyManager::DependencyTree.new(\n  a: [:b, :c],\n  b: [:c],\n  c: []\n)\n```\n\n`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`:\n\n```ruby\n# /lib/dependency_manager/factory.rb \u003e Singleton methods\n\ndef parameters\n  instance_method(:initialize).parameters\nend\n\ndef dependencies\n  dependencies = parameters\n    .select { |type, _name| KEYWORD_ARGS.include?(type) }\n    .map(\u0026:last)\n\n  dependencies - CONTEXT_DEPENDENCIES\nend\n\ndef factory_dependencies\n  dependencies.map { |d| \"#{d}_factory\".to_sym }\nend\n```\n\nSo our above hypothetical `initialize` method:\n\n```ruby\ndef initialize(logger:, other:, optional: nil)\n```\n\n...would give us the following dependency chain:\n\n```ruby\n[:logger_factory, :other_factory, :optional_factory]\n```\n\nIt 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`.\n\n#### Container Ordering Dependencies\n\nGiven these `TSort`, which is included in `DependencyTree`, can figure out what order to load dependencies in. Taking a look at our above:\n\n```ruby\n# /spec/dependency_manager/dependency_tree_spec.rb\ntree = DependencyManager::DependencyTree.new(\n  a: [:b, :c],\n  b: [:c],\n  c: []\n)\n\ntree.tsort\n# =\u003e [:c, :b, :a]\n```\n\nIt would run `c` then `b` then `a`, which makes sense as `c` has no other dependencies.\n\n`TSort` is also kind enough to keep us from creating cycles by accident:\n\n```ruby\n# /spec/dependency_manager/dependency_tree_spec.rb\ntree = DependencyManager::DependencyTree.new(\n  a: [:b, :c],\n  b: [:c],\n  c: [:b] # LOOP\n)\n\ntree.tsort\n# raises TSort::Cyclic\n```\n\n#### Container Resolving Dependencies\n\n```ruby\n# /lib/dependency_manager/container.rb\nresolved_dependencies = Resolver.new(\n  factory: factory,\n  loaded_dependencies: dependencies\n).resolve\n```\n\nAs 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`.\n\n`/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.\n\n#### Container Building Dependencies\n\nOnce we have the dependencies we can inject hte rest of the information we need, and we now have a factory ready to be built:\n\n```ruby\n# /lib/dependency_manager/container.rb\nfactory_instance = factory.new(\n  app_context:    @app_context,\n  factory_config: get_config(factory),\n  **resolved_dependencies\n)\n```\n\n...once ready we turn around and build it:\n\n```ruby\n# /lib/dependency_manager/container.rb\n@dependencies[factory.dependency_name] = factory_instance.build\n```\n\n`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.\n\nThis 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.\n\n#### Container Presenting Dependencies\n\nOnce that's done all of the dependencies have been created and you can get them out in a few ways:\n\n```ruby\n# Modified from: /spec/dependency_manager/container_spec.rb\n\nAppContext = Struct.new(:name, :env)\n\ncontainer = DependencyManager::Container.new(\n  app_context:   AppContext.new('README', 'test'),\n  configuration: {\n    logger:      { enabled: true, level: :info },\n    flags:       { enabled: true, default_values: { a: 1, b: 2, c: 3 } },\n    timing:      { enabled: true },\n    hype_person: { enabled: true }\n  },\n  factories: DependencyManager::Factory.factories\n)\n\ncontainer.build\n# All dependencies returned here too, but prefer to use the next two methods\n\ncontainer.fetch(:logger)\n# =\u003e instance_of Logger\n\ncontainer.to_h\n# {\n#   logger:      instance_of Logger,\n#   flags:       instance_of Flags,\n#   timing:      instance_of Timing,\n#   hype_person: instance_of HypePerson\n# }\n```\n\n...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.\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'dependency_manager'\n```\n\nAnd then execute:\n\n    $ bundle\n\nOr install it yourself as:\n\n    $ gem install dependency_manager\n\n## Development\n\nAfter 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.\n\nTo 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).\n\n## Contributing\n\nBug 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.\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).\n\n## Code of Conduct\n\nEveryone 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).\n","funding_links":[],"categories":["Ruby"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbaweaver%2Fdependency_manager","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbaweaver%2Fdependency_manager","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbaweaver%2Fdependency_manager/lists"}