Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
:toc: macro :toclevels: 5 :figure-caption!:
:dependency_injection_containers_link: link:https://alchemists.io/articles/dependency_injection_containers[Dependency Injection Containers] :infusible_link: link:https://alchemists.io/projects/infusible[Infusible] :rspec_link: link:https://rspec.info[RSpec] :test_doubles_link: link:https://alchemists.io/articles/rspec_test_doubles[Test Doubles]
= Containable
This gem provides a thread-safe container for defining dependencies for reuse within your application. Coupled with the {infusible_link} gem, this powerful combination makes {dependency_injection_containers_link} simple to implement, test, and maintain.
toc::[]
== Features
== Requirements
. link:https://www.ruby-lang.org[Ruby]. . A strong understanding of {dependency_injection_containers_link}.
== Setup
To install with security, run:
To install without security, run:
You can also add the gem directly to your project:
Once the gem is installed, you only need to require it:
== Usage
You can immediately use this gem by creating a container, extending the container with functionality from this gem, and register any/all dependencies as desired. Example:
require "containable"
module Container extend Containable
register :literal, 1 register(:echo) { |text| text } end
The rest of this section will expand upon what is shown above.
=== Modules
Containers must be modules. For example, attempting to turn a class into a container is not allowed:
require "containable"
class Container extend Containable end
This is important since containers are only meant to hold your dependencies and nothing else. Modules are perfect for this.
=== Registration
As shown above, the best way to register dependencies is as you define your container. The most basic is via a key/value pair:
require "containable"
module Container extend Containable
With the above, 1
(literal) will be associated with the :demo
key. This is perfect for registering literals, constants, or any objects you immediately want evaluated or have a reference to. To lazily register a dependency, use a block with parameters:
require "containable"
module Container extend Containable
In this case the :demo
key is associated with an instance of an object but the instance will only be realized when first resolved. Until the :demo
key is resolved, the object is not instantiated and remains a closure (more on resolving dependencies shortly). You can also register procs, lambdas, and functions in the same manner:
require "containable"
function = proc { 3 }
module Container extend Containable
As you can see, registration is quite flexible. That said, you only register either a value or closure but not both. For example, if you register both a value and a closure you'll get a warning (as printed as standard error output):
require "containable"
module Container extend Containable
register(:demo, "bogus") { 1 } end
While providing the value isn't harmful, it is unnecessary and wasteful. Instead, supply a value or a closure but not both.
You can also register dependencies after the fact since the container is open, by default. Example:
require "containable"
module Container extend Containable
register :one, 1 end
With the above, a combination of .register
and .[]=
(setter) messages are used. While the latter is handy the former should be preferred for improved readability.
⚠️ Due to registration being flexible to begin with, avoid nesting closures. Example:
register(:sanitizer) { -> content { Sanitize.fragment content, Sanitize::Config::BASIC } }
While the former will work, there is no benefit to nesting like this. The latter is more performant because you don't have to unwrap the nested closure to achieve the same functionality since there is nothing to achieve from the lazy resolution of the sanitize functionality.
=== Resolution
Now that you understand how to register dependencies, we can talk about resolving them. There are two ways to resolve a dependency. Example:
Both messages are acceptable but using .[]
(getter) is recommended due to being succinct, requires less typing, and allows the container to feel more like a Hash
. Internally, when resolving a dependency, all keys are stored as strings which means you can use symbols or strings interchangeably except when using namespaces (more on this shortly). Example:
When discussing registration earlier, we saw you can register values and closures. A value can also be a closure but if a block is registered -- in addition to the value -- the block takes precedence over the value.
What hasn't been discussed is the kind of closure used when registering a value or block. If a closure takes no parameters, then the closure will be resolved immediately when resolving the key for the first time. Any closure that takes one more more parameters will never be resolved which means you can call the closure directly when needed. To illustrate, consider the following:
require "containable"
module Container extend Containable
register :one, proc { 1 } register(:two) { |text| text.upcase } register :three, -> text { text.reverse } end
With the above, you can see :one
was immediately resolved to the value of 1
even though it was wrapped in a closure to begin with. This happened because the closure had no parameters so was safe to resolve. Again, this allows you to lazily resolve a dependency until you need it.
For keys :two
and :three
, we have a closure that has at least one parameter so remains a closure so you can supply the arguments you need later. Here's a closer look of using the :two
and :three
dependencies:
In all of these situations, we have closures supplied as values or blocks but only closures with out parameters are resolved (i.e. unwrapped).
=== Namespaces
As hinted at earlier, you can namespace your dependencies for improved organization. Example:
require "containable"
module Container extend Containable
namespace :one do register :blue, "blue" end
namespace :two do register :green, "green" end
There is no limit on the number of namespaces used or how deep they are nested. That said, this functionality should not be abused by sticking to either one or two levels of hierarchy. Anything more than that and you should reflect if your implementation is overly complex in order to refactor accordingly.
As with registration, you can use symbols, strings, or both for your namespaces since they are stored internally as strings. Namespaces are delimited by periods (.
) so you must use a string for your key to resolve them. Example:
=== Enumeration
Limited enumeration of your container is possible. Given the following:
require "containable"
module Container extend Containable
...this means you can use all of the following messages:
Container.each { |key, value| puts "#{key}=#{value}" }
Container.each_key { |key| puts "Key: #{key}" }
Container.key? :one # false Container.key? "one" # true
=== Freezing
You can freeze your container and immediately check if it is frozen. Example:
require "containable"
module Container extend Containable
register :demo, "An example." freeze end
You can also freeze your container after the fact by messaging .freeze
directly on the container: Container.freeze
. Once a container if frozen, registration of additional dependencies will result in an error:
Container.register :another, "One more."
Once frozen, the container can't be unfrozen unless you duplicate it (see below).
=== Duplicates
You can duplicate a container via the following (which will unfreeze the container if previously frozen):
container = Container.dup container.name
Other = Container.dup Other.name
As you can see a container, once duplicated, can be assigned to a local variable or a new constant. When assigning to a variable, the container will use a temporary name of containable
for identification.
=== Clones
Cloning a container is identical to duplicating a container except if the container is frozen then the clone will be frozen too. Example:
=== Customization
You can customize how the container registers and resolves dependencies by creating your own register and resolver objects. For example, here's how to use a custom register that doesn't care if you override an existing key.
require "containable"
class CustomRegister < Containable::Register def call(key, value = nil, &block) = dependencies[namespacify(key)] = block || value end
module Container extend Containable[register: CustomRegister]
register :one, 1 register :one, "override" end
...and here's an example with a custom resolver that only allows specific keys to be resolved:
require "containable"
class CustomResolver < Containable::Resolver def initialize , allowed_keys: %i[one three] super() @allowed_keys = allowed_keys end
def call key fail KeyError, "Only use these keys: #{allowed_keys.inspect}" unless allowed_keys.include? key
super
end
private
attr_reader :allowed_keys end
module Container extend Containable[resolver: CustomResolver]
register :one, 1 register :two, 2 register :three, 3 end
In both cases, you only need to inject your custom register or resolver when extending your container with Containable
. Both of these classes should inherit from either Containable::Register
or Containable::Resolver
to customize behavior as you like. Definitely check out the source code of both these classes to learn more and customize as desired.
=== Infusible
To fully leverage the power of this gem, check out {infusible_link}. You can get far with simple containers but if you want to supercharge your containers and make your architecture truly come alive then make sure to couple this gem with the {infusible_link} gem. 🚀
=== Tests
As you architect your implementation, you'll want to swap out your original dependencies with {test_doubles_link} to simplify testing especially for situations, like making HTTP requests, with a fake. For demonstration purposes, I'll assume you are using {rspec_link} but you can adapt for whatever testing framework you are using.
Consider the following:
module Container extend Containable
register :kernel, Kernel end
class Demo def initialize container: Container @container = container end
def speak(text) = kernel.puts text
private
attr_reader :container
With our implementation defined, we can test as follows:
RSpec.describe Demo do subject(:demo) { Demo.new }
let(:kernel) { class_spy Kernel }
before { Container.stub! kernel: } after { Container.restore }
Notice there is little setup required to test the injected dependencies. Simply define what you want stubbed in 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:
RSpec.shared_context "with application dependencies" do let(:kernel) { class_spy Kernel }
RSpec.describe Demo do subject(:demo) { Demo.new }
include_context "with application dependencies"
You'll notice, in all of the examples, only two methods are used: .stub!
and .restore
. The first allows you supply keyword arguments of all dependencies you want stubbed. The last ensures your test suite is properly cleaned up so all stubs are removed and the container is restored to it's original state. If you don't restore your container after each spec, you'll end up with stubs leaking across your specs and {rspec_link} will error to the same effect as well.
Always use .stub!
to set your container up for testing. Once setup, you can add more stubs by using the .stub
method (without the bang). So, to recap, use .stub!
as a one-liner for setup and initial stubs then use .stub
to add more stubs after the fact. Finally, ensure you restore (i.e. .restore
) your container for proper cleanup after each test.
‼️ Use of .stub!
, while convenient for testing, should -- under no circumstances -- be used in production code because it is meant for testing purposes only.
== Development
To contribute, run:
You can also use the IRB console for direct access to all objects:
== Tests
To test, run:
== link:https://alchemists.io/policies/license[License]
== link:https://alchemists.io/policies/security[Security]
== link:https://alchemists.io/policies/code_of_conduct[Code of Conduct]
== link:https://alchemists.io/policies/contributions[Contributions]
== link:https://alchemists.io/policies/developer_certificate_of_origin[Developer Certificate of Origin]
== link:https://alchemists.io/projects/containable/versions[Versions]
== link:https://alchemists.io/community[Community]
== Credits
FAQs
Unknown package
We found that containable demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.