I am looking to do some method chaining. I have the following code:
class MyClass
attr_accessor :handler
def do_a
puts 'i just did a'
self.handler = 'a'
self
end
def do_b_if_a
puts 'i just did b' if handler == 'a'
end
end
So the following works:
irb > test = MyClass.new
=> #<MyClass:0x007fa44ced9a70 @handler=nil>
irb > test.do_a
'i just did a'
irb > test.do_a.do_b_if_a
'i just did a'
'i just did b'
What I DONT want to work is when I call do_a the first time it sets the handler, which means now do_b_if_a can be called at any time. But I only want it to be called when it is chained with do_a, how do I do that?
I think you’re tracking state in the wrong place. You’d be better off with something similar to ActiveRecord’s query interface, for example:
That way you always have an instance of MyClass but you have a throw-away copy that keeps track of its history. This is similar to cHao’s approach but it doesn’t need an extra decorator class as MyClass can decorate itself.