Thursday, June 21, 2012

dependency injection minimal (dim) gem v1.2 released

I just released v1.2 of the dependency injection minimal gem (dim). Originally this project was just a gemification of Jim Weirich's example code, but v1.2 marks my first meaningful feature addition.

dim aims to provide a simple, Ruby-esque way to handle dependency injection. I find myself using it in all of my projects as a way to consolidate into one file all of the configuration that my apps need.

I noticed a common pattern, though. I had started to use dim to encapsulate ENV variables, so that my code would not need to know the source of a configuration variable (usually an API key or a URI for accessing a third-party service); in the test environment, the source might be a hard-coded literal string, but in production it might come from an actual ENV variable.

So I added a register_envmethod to complement the register method that Jim originally added. Below is an example of how I'm using it.

# attempts to read ENV["API_PASSWORD"], otherwise makes sure that the parent container has
# a service named api_password registered
The above code will fail if you don't have ENV["API_PASSWORD"] defined, or if ServerContainer doesn't have a parent container with :api_password set. Typically I'm using a YAML file to populate ServerContainer's parent with sensitive values that I want to have in my development environment (and then I make sure to ignore that file in source control).

See the docs or the source code for more details.

No comments: