1. Introduction

1.1. What is Needle?

Needle is a dependency injection (also, inversion of control) container for Ruby.

1.2. How Can It Help Me?

So, what can Needle do for you? Ultimately, it can reduce the amount of code that you have to write, simplifying many common programming tasks for you. This has the two-fold benefit of both decreasing application development time, and of decreasing the effort needed to maintain your application.

But what, specifically, can Needle do for you?

Try these on for size:

(Thanks to Howard Lewis Ship for his HiveMind documentation, from which some of the above bullet points were adapted.)

Log Method Execution

Needle has an integrated logging framework, and the ability to log execution trace information without modifying a single line of code in your classes. This means that you can easily see what methods get called, with what arguments, and what the return values are, all without having to physically modify any of your classes.

Consider the following code, demonstrating how this would be done without Needle:

  def foo( arg1, arg2 )
    @log.debug( "in foo with #{arg1} and #{arg2}" ) if @log.debug?
    ...
    result = the_result_of_the_method
    @log.debug( "finishing foo with #{result}" ) if @log.debug
    return result
  rescue Exception => e
    @log.debug( "foo raised exception #{e.message} (#{e.class})" ) if @log.debug?
    raise
  end

Now, multiply that by the number of methods in your class… the logging messages quickly overpower the rest of the code, and detract from the flow of your program. This makes your program harder to debug, test, and maintain.

Now, consider the same method using Needle’s integrated logging framework…

  def foo( arg1, arg2 )
    ...
    return the_result_of_the_method
  end

Then, when you define the service that you want to add the logging to:

  registry.register( :service_name_here ) { |reg| ... }
  registry.intercept( :service_name_here ).with! { logging_interceptor }

That’s right. There’s no explicit logging code in there. Instead, you just tell Needle that the methods of the class should be logged, and away it goes. This has the added benefit of allowing your objects to be unit tested, without spewing log messages everywhere.

Reference Another Service

Invariably in a large application services will reference other services. This is typically accomplished through something like this:

  class Component
    ...
    def foo( parms )
      @service ||= lookup_service
      @service.do_something( parms )
    end

    def lookup_service
      ...
    end
    ...
  end

Whether the lookup is done lazily, as shown above, or when the class is first instantiated is irrelevant. The point is that you either have to implement a bunch of code to look up a service based on some criteria, or you hard code the class of the service (which creates tight coupling and makes things like unit testing harder).

With Needle, you just declare a setter for the service, and then tell Needle that the class depends on the other service:

  class Component
    attr_writer :service
    ...
    def foo( parms )
      @service.do_something( parms )
    end
    ...
  end

  registry.register( :component ) do |reg| 
    c = Component.new
    c.service = reg.some_other_service
    c
  end

Then, when your service is instantiated, Needle will automatically look for and instantiate the dependencies for you. This makes for cleaner code, and looser coupling between services.

Unit Testing

Large applications can prove troublesome to unit test exhaustively, especially if there is any kind of tight coupling between components. Such coupling of components can make it difficult to test them separately.

Needle, by its very nature, encourages loose coupling of components. Also, because dependencies are never instantiated in code, but are instead accepted via setters or constructor arguments, it is trivial to replace those dependencies with mock objects at unit test time.

Consider this tightly coupled example:

  def foo( args )
    @some_dependency ||= MyNewDependency.new
    @some_dependency.do_something(args)
  end

It is impossible to test the method #foo without also testing the MyNewDependency class. However, if the @some_dependency object is made a property that is set externally, you can replace it at test time with a blank:

  attr_writer :some_dependency

  def foo( args )
    @some_dependency.do_something( args )
  end

The unit test would become something like this:

  def test_foo
    @obj.some_dependecy = MyMockDependency.new
    @obj.foo( args )
    assert @obj.is_in_some_state
  end

Lifecycle Management

Singleton objects are a fact of life in complex systems. The singleton design pattern is powerful and useful. However, using the Singleton mixin, or declaring methods at the class level, can make your code difficult to unit test since the state of such objects cannot be easily reset.

Needle has a solution. You can tell Needle to treat a service as either a prototype service (meaning it will be instantiated every time you ask for it, like calling #new), or a singleton service (meaning it will only be instantiated once, and the same instance will be returned for subsequent requests).

Your object is still just a plain ol’ ordinary Ruby object, but Needle has effectively transformed it into a singleton. This means you can unit test it as if it were nothing special, but when it is used in your application it will act like a singleton.

Lifecycle management also means that you can control when a service is instantiated. The prototype and singleton models will always be instantiated as soon as they are requested. Sometimes, though, you don’t want that—you’d like the instantiation to be deferred as late as possible.

With Needle, you can indicate that a service should use deferred instantiation. This will cause the service to not actually be instantiated until a method is actually invoked on it. Using this model, you can have services depend on themselves, or other forms of cyclical dependencies.

1.3. Alternatives

Needle is not the only fish in the dependency-injection pond, even when it comes to Ruby. Other containers at your disposal include:

  • Copland. Copland aims to be an “application framework”, taking something of a heavy-weight approach to DI. In so doing, it provides functionality that Needle does not, but at the cost of performance. It also uses external (YAML) configuration files. It is inspired by a Java framework (HiveMind), and so has a vaguely Java-ish flavor to it.
  • Rico. Rico is another project inspired by a Java project (PicoContainer). It is very lean, and appears to be experimental.
  • Tudura. I do not have any information on this project, as the information is all in Japanese. If someone with more information about Tudura would like to step forward, I’d be happy to post a summary here.

There is, at the time of this writing, at least one other project on RubyForge devoted to DI, although it has no public releases yet.

So, which one should you choose? It comes down to an issue of personal preference, mostly, but also one of what you are wanting to accomplish. Needle excels at providing an unobtrusive, light-weight container for managing your dependencies. The cost of it being light-weight is that there is functionality it does not provide, which other containers may. If you really need that missing functionality, you are required to either implement it yourself, or select a different container.

For most tasks, I think you’ll find Needle more than sufficient.

1.4. License Information

Needle is made available under either the BSD license, or the same license Ruby (which, by extension, also allows the GPL as a permissable license as well). You can view the full text of any of these licenses in the doc subdirectory of the Needle distrubtion. The texts of the BSD and GPL licenses are also available online: BSD and GPL.

This manual (in any form, be it source or otherwise) and the scripts and templates used to generate it, are all distributed under the Creative Commons Attribution-ShareAlike license.

If you desire permission to use either Needle or the manual in a manner incompatible with these licenses, please contact the copyright holder (Jamis Buck) in order to negotiate a more compatible license.

1.5. Support

Mailing lists, bug trackers, feature requests, and public forums are available (courtesy of RubyForge) at Needle’s RubyForge project page. Just direct your browser to http://rubyforge.org/projects/needle.