Strudel is a dependency injection container for Ruby. It's a way to organize your Ruby application to take advantage of the dependency inversion principle.
Why another DI framework?
Strudel is not a framework. It's one class that serves as a container only. No auto-injection. That means no polluting your classes with garbage injection metaprogramming. You have full, explicit control over how your services are constructed.
Honestly, you may not even need Strudel or any other DI library. If you are passing your dependencies through your class constructors, you're already doing dependency injection! Strudel simply helps you organize your services and dependencies in one place.
But Ruby Doesn't Need Dependency Injection!
You may have read this post by David Heineimer Hansson. However he didn't address the primary benefit of DI, explicitly defining dependencies. I also happen to think that patching code at runtime for testing is an egregious anti-pattern. In case you need more convincing, check out this great post by Piotr Solnica.
Add this line to your application's Gemfile:
Fist create a new instance of
require 'strudel' app = .
The methods you will use most often are
set. These allow you to
create and access services.
# Set a static service app[:api_url] = 'http://example.com/api' # Set a shared service app.set(:api) do RestApi.new(app[:api_url]) end # Now we can access the api service app[:api].request
In this example, we set up and use an
- First we use the
=method to create a static service called
- Then we create a service called
api. This time we pass a block into the
setmethod. This allows the service to be instantiated asynchronously. The
RestApiinstance won't be created until we use it on the final line.
- On the last line, we use the
method to retrieve the instance of
RestApiand call a
requestmethod on it. Because of the way we defined the
api.urlparameter will be passed into the
RestApiconstructor when it is created.
Once it's constructed, the
api service will be cached, so if we call it again,
Strudel will use the same instance of
See the API Documentation for more information or to learn about the other available methods:
API documentation can be found at rubydoc.info, or you can generate HTML documentation with yard.
The gem is available as open source under the terms of the MIT License.