From: Joel VanderWerf Date: 2010-11-03T05:35:28+09:00 Subject: Re: Inversion of Control in Ruby by passing classes - does it make any sense? On 11/02/2010 01:01 PM, Manuel Kiessling wrote: > Hello everyone, > > I'm quite new to Ruby, with a strong background in PHP. > > I had a great time finding my way around in Ruby, because it is a fantastic language. However, right now I'm a bit stuck regarding the issue of loose coupling / inversion of control / writing testable units. > > I spent the last days reading a lot of articles, but feel sort of puzzled now. > > As far as I can see, there are several approaches. I will start with my own, which probably is the weirdest of all - feel free to dissect it. > > Let's say I have 2 classes, SomeClass and OtherClass, and SomeClass depends on OtherClass, because in some cases it needs to create an instance of this class, and in others it doesn't, which is why we can't simply pass an already created instance of OtherClass into SomeClass. > > This is how it could be done using no DI at all: > > class SomeClass > def do_something(a, b) > c = a + b > if (c> 5) then > o = OtherClass.new() > o.log(c) > end > end > end One way to do it (assuming you want to reuse the OtherClass instance): class SomeClass def do_something(a, b) c = a + b if c > 5 otherclass.log(c) end end def otherclass @otherclass ||= OtherClass.new end end mock = SomeClass.new mock.otherclass = MockOtherClass.new # or whatever # note, you will have to define a writer # (or use instance_variable_set)