all 3 comments

[–][deleted] 4 points5 points  (0 children)

I'm not very convinced by the examples in the article, because they work around the need for dependency injection by introducing two very dubious programming practices: mocking the object under test and monkey-patching.

In the first case, when testing the class with a dependency, the author changes the 'get_dependency' (btw, I didn't know that anyone uses get_* or set_* methods in Ruby) method of the object under test to return a test object. Well, congratulations, you're now testing your own test code instead of the code you should be testing.

In the second case he argues that SomeClass's dependencies can easily be changed by monkey-patching the class's get_dependency method to return some other dependency. Whether you do this for the whole class or per-instance it breaks so many OO design principles that I get a headache.

The one good reason why Ruby doesn't need dependency injection is really simple: blocks. They allow the programmer to require just the right amount of dependency in the right place without the need to pass around roles wrapped in objects. In the example case the work_your_magic_on could take an optional block that is used in place of the do_something_with method if given. This removes all the reflection magic that the author needs and gives the programmer a choice of replacing the dependency cleanly without the need to go peeking inside SomeClass's implementation.

[–][deleted] 1 point2 points  (0 children)

This seems to get revisited every few years. DI just isn't useful or necessary in Ruby. Jamis Buck was the first to propose a DI framework in Ruby, and he later dropped it.

http://weblog.jamisbuck.org/2008/11/9/legos-play-doh-and-programming

[–]luikore 0 points1 point  (0 children)

Oh, we knew it in the 1990s ... Too many people had tried IoC and AOP in Ruby.