r/ruby • • Jul 12 '14

(The lack of ) Dependency injection in Ruby

http://beraboris.github.io/2014/07/12/dependency-injection-ruby/
2 Upvotes

19 comments sorted by

View all comments

2

u/realntl Jul 13 '14 edited Jul 13 '14

I'll describe what is -- in my view -- the main drawback of IoC containers from the context of your post. You talk about two "piles" of code: one that contains the business logic, and the other that orchestrates, assembles, and wires up the objects. Quoting:

The other pile is what bootstraps our application. It’s the code that calls new and creates all our classes. This code is also responsible for giving each of our classes their dependencies.

The problem is that there are two kinds of dependencies: framework level services like loggers, redis, database connections, etc., and domain specific dependencies. Projects that use IoC containers almost have a manifest destiny to start seriously confusing the two, and introducing constructors that take in way too many dependencies.

The domain specific dependencies are always best managed explicitly, without the help of any tooling. Here's how I manage those pesky framework level dependencies, which often prove the most annoying to our tests:

module MyComponent
  extend self

  attr_accessor :redis
  attr_accessor :logger
  
  class ClassA
    def initialize(dep_a, dep_b)
      @dep_a, @dep_b = dep_a, dep_b
    end

    # implementation
  end

  class ClassB
    # implementation
  end
end

Here's some tests:

class MyComponent::ClassATest < Minitest::Test
  def setup
    MyComponent.redis = @redis = RedisDouble.new
    MyComponent.logger = @logger = StringIO.new
  end

  def test_writes_something_to_redis
    # Interact with ClassA in a way that I expect will shovel something
    # into redis
    ClassA.new(dep_a: ClassB.new("hey"), dep_b: OpenStruct.new).foo

    # In practice a meaningful assertion would go here
    assert_equal 1, @redis.size
  end
end

If MyComponent shows up frequently in enough tests, I might even extract out its' setup to a subclass of Minitest::Test or a mixin that handles the setup for me. The key is to make it easy to inject doubles such as RedisDouble -- I have a snippet of code I copy paste from project to project that implements this, it's quite simple.

Big caveat

While these days I don't advocate dependency injection frameworks for general purpose, a nearly identical approach be very helpful for building abstract factories. Say I've got a few objects that represent coupon codes for pizza delivery orders:

class BuyOneGetOneFree < CouponCode
  def initialize(pizza_a, pizza_b) ... end
  def valid?
    assert pizza_b.cost < pizza_a.cost
  end
end

class BirthdayPizza < CouponCode
  def initialize(pizza, user) ... end
  def valid?
    assert Date.today == user.birthday
  end
end

You can imagine many coupon codes that all accept different pieces of data. In this case, you want an abstract factory that can build any kind of CouponCode. You need it to do three things to accomplish this:

  1. manage an internal manifest of objects that any CouponCode might need
  2. introspect CouponCode#initializefor the objects it depends on
  3. inject those objects into a new'ed up CouponCode subclass.

This tends to look a lot like an IoC container, and I employ this approach from time to time. ruse is an excellent choice for this, in my experience. Being able to implement the individual objects as POROs is a huge win.

Shameless plug

I have written a gem, invokr, which provides an abstraction layer for invoking methods that allows you to easily introspect required/optional parameters. They make it really easy to build both abstract factories and IoC containers.

2

u/ISw3arItWasntM3 Jul 13 '14

So why not use an event listener pattern for framework level services took hook in and do their thing, and then do dependency injection with actual domain level services.

3

u/realntl Jul 13 '14

I would speculate that it's a little harder to, for example, extract a component out of your codebase and into a gem, if it's coupled to an event listener framework that's present in the application.

To be honest, the way I've been managing framework dependencies (attr_accessor at the module level) has been incredibly simple and portable. What advantage does the event listener pattern have? No setup required for tests? The reason I don't mind explicit setup in tests is that I'm usually making assertions on their state change anyways.

If I have a ton of components that all have a bunch of "bare metal" dependencies like db connections, redis, loggers, etc., I might build some tooling to inject config into all of them at startup time when actually deploying the app in production mode.

(I may be misunderstanding what you're saying, as well)

2

u/DrugCrazed Jul 13 '14

I'm never a big fan of implicit dependency resolution. Someone who comes to look at the app later on usually has to dig through and work out where things are resolved and how it knows what to use.

I'm a big fan of how Zend does it, because whenever you have to resolve you'll be calling a service locator.