Trying To Understand The Need For Morphine (DI Framework For Ruby)

For a long time now, I had an open tab in my browser with Morphine‘s project page on GitHub. From first look at it, it wasn’t clear to me why would you need such a library in Ruby. I mean, I understand the need for Dependency Injection (DI) in any language (including Ruby). What I didn’t understand was, why would you need a library to do DI in Ruby?

To try and understand better, I decided to rewrite the example shown on the library page with regular class methods. Here’s the result (first file: with Morphine, second file: without Morphine):

After writing this example, it was more clear to me — the Morphine based code is more compact and clean. But on the other hand, it requires the reader of the code to get familiar with another library, where the class methods based example is straight forward to any Ruby developer.

What do you think? Would you use Morphine or go with class methods?

  • liorsion

    Looks like a way for people who didn’t come from ruby to continue doing things the way they are used to 

  • Brandon Keepers

    I started extracting morphine from the stuff we are doing in Gaug.es (http://get.gaug.es). There is only one commit to the project, with the only feature being memoization. I didn’t expect it to start getting attention yet. Previously, Gaug.es looked identical to your second example. But once you get 10-20 services registered, you get sick of seeing `@thing ||= Thing.new`.
    I’ve been using Ruby full time since 2006. I came from Java, where almost every object was instantiated through a dependency injection framework. For the past 6 years, I fully embraced the Ruby way and wrote a lot of code that was tightly coupled to one implementation.Gaug.es has been going through some serious traffic growth recently, so we’ve been slowly replacing components with ones that are more scalable. Thus, we’ve begun decoupling things with dependency injection so we can easily swap out the services that are used at runtime. In production, we use Kestrel. In development, we avoid queues altogether.

  • http://www.arikfr.com/blog/ Arik Fraimovich

    I had a feeling that maybe when you start having bigger container object, the benefits of using Morphine are more apparent.

    Also I wanted to suggest that you add this explanation to the project page, but I see that you already did… :-)  

    Thanks for taking the time to comment here!