Automatically injects dependencies within your object via the Dependency Inversion Principle — the D in SOLID design — and is a powerful way to compose complex architectures from small objects which leverage the Single Responsibility Principle — the S in SOLID design.
When coupled with Dependency Injection Containers, as provided by the Containable gem, Infusible completes the second half of the Dependency Inversion Principle. Here’s a quick example of Infusible in action:
Import = Infusible[a: 1, b: 2, c: 3]
class Demo
include Import[:a, :b, :c]
def to_s = "My injected dependencies are: #{a}, #{b}, and #{c}."
end
puts Demo.new # My injected dependencies are: 1, 2, and 3.
By infusing dependencies into your object, you have the ability to define common dependencies that can be injected without the manual setup normally required to define a constructor, set private instance variables, and set private attribute readers.
-
Ensures injected dependencies are private by default but has support for public and protected injection.
-
Built atop the Marameters gem.
-
Ruby.
-
Knowledge of SOLID design principles.
To install with security, run:
# 💡 Skip this line if you already have the public certificate installed.
gem cert --add <(curl --compressed --location https://alchemists.io/gems.pem)
gem install infusible --trust-policy HighSecurity
To install without security, run:
gem install infusible
You can also add the gem directly to your project:
bundle add infusible
Once the gem is installed, you only need to require it:
require "infusible"
There is basic and advanced usage. We’ll start with the basics and work our to more advanced usage.
This gem requires three steps for proper use:
-
A container.
-
An import constant.
-
An object and/or multiple objects for dependencies to be injected into.
Let’s walk through each staring by defining a container of dependencies.
A container provides a common object for which you can group related dependencies for injection and reuse. Containable is recommended for defining your dependencies but a primitive Hash
or any object which responds to the #[]
message works too.
For documentation purposes, the Containable gem will be used. The following creates a simple container where you might want to use the HTTP gem to make HTTP requests and log information using Ruby’s native logger.
require "containable"
require "http"
require "logger"
module Container
extend Containable
register :http, HTTP
register(:logger) { Logger.new STDOUT }
end
Once your container is defined, you’ll want to define the corresponding import for reuse within your application. Defining an import only requires two lines of code:
require "infusible"
Import = Infusible[Container]
With your container and import defined, you can inject your dependencies by including what you need:
class Pinger
include Import[:http, :logger]
def call url
http.get(url).status.then { |status| logger.info %(The status of "#{url}" is #{status}.) }
end
end
Now when you ping a URL, you’ll see the status of the server logged to console using all injected dependencies:
Pinger.new.call "https://duckduckgo.com"
# I, [2022-03-01T10:00:00.979741 #81819] INFO -- : The status of "https://duckduckgo.com" is 200 OK.
When injecting your dependencies you must always define what dependencies you want to require. By default, none will be injected. The following demonstrates multiple ways to manage the injection of your dependencies.
You can use symbols, strings, or a combination of both when defining which dependencies you want to inject. Example:
class Pinger
include Import[:http, "logger"]
def call = puts "Using: #{http.inspect} and #{logger.inspect}."
end
To access namespaced dependencies within a container, you only need to provide the fully qualified path. Example:
class Pinger
include Import["primary.http", "primary.logger"]
def call = puts "Using: #{http.inspect} and #{logger.inspect}."
end
The namespace (i.e. primary
) and delimiter (i.e. .
) will be removed so only http
and logger
are defined for use (as shown in the #call
method). Only dots (i.e. .
) are allowed as the delimiter between namespace and dependency.
Should you want to rename your namespaced dependencies to something more appropriate for your class, use a hash. Example:
class Pinger
include Import[client: "primary.http"]
def call = puts "Using: #{client.inspect}."
end
The aliased "primary.http"
will be defined as client
when imported (as shown in the #call
method).
You can also mix names, namespaces, and aliases for injection as long as the aliases are defined last. Example:
class Pinger
include Import[:configuration, "primary.logger", client: :http]
def call = puts "Using: #{configuration.inspect}, #{logger.inspect}, and #{client.inspect}."
end
Earlier, when demonstrating basic usage, all dependencies were injected by default:
class Pinger
include Import[:http, :logger]
end
…but we could have a different class — like a downloader — that only needs the HTTP client. In that case, we could import the same container but only require the HTTP dependency. Example:
class Downloader
include Import[:http]
end
This allows you to reuse Import
in as many situations as makes sense while improving performance.
Should you want to use injection in combination with your own initializer, you’ll need to ensure the injected dependencies are passed upward. All you need to do is define the injected dependencies as your last argument and then pass them to super
. Example:
class Pinger
include Import[:logger]
def initialize(http: HTTP, **)
super(**)
@http = http
end
private
attr_reader :http
end
The above will ensure the logger gets passed upwards to the superclass while remaining accessible by the subclass.
When using inheritance (or multiple inheritance), the child class' dependencies will take precedence over the parent’s dependencies as long as the keys are the same. Consider the following:
class Parent
def initialize logger: Logger.new(StringIO.new)
@logger = logger
end
private
attr_reader :logger
end
class Child < Parent
include Import[:logger]
end
In the above situation, the child’s logger will be the logger that is injected which overrides the default logger defined by the parent. This applies to multiple inheritance too. Example:
class Parent
include GeneralImport[:logger]
end
class Child < Parent
include Import[:logger]
end
Once again, the child’s logger will take precedence over the what is provided by default by the parent. This also applies to multiple levels of inheritance or multiple inherited modules. Whichever is last to be injected, wins. Lastly, you can mix and match dependencies too:
class Parent
include Import[:logger]
end
class Child < Parent
include Import[:http]
end
With the above, the child class will have access to both the logger
and http
dependencies.
protected
by your parent objects in order to avoid breaking the parent/child relationship.
By default — and in all of the examples shown so far — your dependencies are private by default when injected but you can make them public or protected. Here’s a quick guide:
-
include Import[:logger]
: Injects a private logger dependency. -
include Import.protected(logger)
: Injects a protected logger dependency. Useful with inheritance and a subclass that needs access to the dependency. -
include Import.public(:logger)
: Injects a public logger dependency.
There is no #private
method since #[]
does this for you and is recommended practice. Use of #public
and #protected
should be used sparingly or not at all if you can avoid it. Here’s an example where public, protected, and private dependencies are injected:
module Container
extend Containable
register :one, "One"
register :two, "Two"
register :three, "Three"
end
Import = Infusible[Container]
class Demo
include Import.public(:one)
include Import.protected(:two)
include Import[:three]
end
demo = Demo.new
demo.one # "One"
demo.two # NoMethodError: protected method.
demo.three # NoMethodError: private method.
You have access to the keys of all dependencies via the private #infused_keys
method which is powerful in metaprogramming situations. For example, consider the following which calls all injected dependencies since they have the same Object API (i.e. #call
):
Example:
module Container
extend Containable
register :one, "One"
register :two, "Two"
end
Import = Infusible[Container]
class Demo
include Import[:one, :two]
def call = infused_keys.each { |key| puts __send__(key) }
end
Demo.new.call
# One
# Two
As you can see, with the private #infused_keys
attribute reader, we are able to iterate through each infused key and send the #call
message to each injected dependency.
Since #infused_keys
is a private attribute reader, this means the infused keys are private to each instance. This includes all ancestors when using inheritance as each parent class in the hierarchy will have it’s own unique array of infused keys depending on what was injected for that object.
All infused keys are frozen by default.
As you architect your implementation, you’ll want to test your injected dependencies. You might want to stub, mock, or spy on them as well. Test support is primarily provided via the Containable gem. Example:
# Our container with a single dependency.
module Container
extend Containable
register :kernel, Kernel
end
# Our import which defines our container for potential injection.
Import = Infusible[Container]
# Our action class which injects our kernel dependency from our container.
class Action
include Import[:kernel]
def call = kernel.puts "This is a test."
end
With our implementation defined, we can test as follows:
RSpec.describe Action do
subject(:action) { Action.new }
let(:kernel) { class_spy Kernel }
before { Container.stub! kernel: }
after { Container.restore }
describe "#call" do
it "prints message" do
action.call
expect(kernel).to have_received(:puts).with("This is a test.")
end
end
end
Notice there is little setup required to test the injected dependencies. You only need to stub and restore via your before
and after
blocks. That’s it!
While the above works great for a single spec, over time you’ll want to reduce duplicated setup by using a shared context. Here’s a rewrite of the above spec which significantly reduces duplication when needing to test multiple objects using the same dependencies:
# spec/support/shared_contexts/application_container.rb
RSpec.shared_context "with application dependencies" do
let(:kernel) { class_spy Kernel }
before { Container.stub! kernel: }
after { Container.restore }
end
# spec/lib/action_spec.rb
RSpec.describe Action do
subject(:action) { Action.new }
include_context "with application dependencies"
describe "#call" do
it "prints message" do
action.call
expect(kernel).to have_received(:puts).with("This is a test.")
end
end
end
A shared context allows for reuse across multiple specs by including it as needed.
To contribute, run:
git clone https://github.com/bkuhlmann/infusible
cd infusible
bin/setup
You can also use the IRB console for direct access to all objects:
bin/console
This gem automates a lot of the boilerplate code you’d manually do by defining your constructor, initializer, and instance variables for you. Normally, when injecting dependencies, you’d do something like this (using the Pinger
example provided earlier):
class Pinger
def initialize http: HTTP, logger: Logger.new(STDOUT)
@http = http
@logger = logger
end
def call url
http.get(url).status.then { |status| logger.info %(The status of "#{url}" is #{status}.) }
end
private
attr_reader :http, :logger
end
When you use this gem all of the construction, initialization, and setting of private instance variables is taken care of for you. So what you see above is identical to the following:
class Pinger
include Import[:http, :logger]
def call url
http.get(url).status.then { |status| logger.info %(The status of "#{url}" is #{status}.) }
end
end
Your constructor, initializer, and instance variables are all there. Only you don’t have to write all of this yourself anymore. 🎉
When using this gem, along with a container like Containable, make sure to adhere to the following guidelines:
-
Use containers to group related dependencies that make logical sense for the namespace you are working in and avoid using containers as a junk drawer for throwing random objects in.
-
Use containers that don’t have a lot of registered dependencies. If you register too many dependencies, that means your objects are too complex and need to be simplified further.
-
Use the
Import
constant to define what is possible to import much like you’d use aContainer
to define your dependencies. Defining what is importable improves performance and should be defined in separate files for improved fuzzy file finding. -
Use
**
to forward keyword arguments when defining an initializer which needs to pass injected dependencies upwards. -
Prefer
Import#[]
over the use ofImport#public
and/orImport#protected
as much as a possible since injected dependencies should be private, by default, in order to not break encapsulation. That said, there are times where making them public and/or protected can save you from writing boilerplate code.
-
Built with Gemsmith.
-
Engineered by Brooke Kuhlmann.