Ruby forwarding method calls
- by JP
I have an instance of a master class which generates instances of a subclass, these subclasses need to forward some method calls back to the master instance.
At the moment I have code looking something like this, but it feels like I should be able to do the same thing more efficiently (maybe with method_missing?)
class Master
def initalize(mynum)
@mynum = mynum
end
def one_thing(subinstance)
"One thing with #{subinstance.var} from #{@mynum}"
end
def four_things(subinstance)
"Four things with #{subinstance.var} from #{@mynum}"
end
def many_things(times,subinstance)
"#{times} things with #{subinstance.var} from #{@mynum}"
end
def make_a_sub(uniqueness)
Subthing.new(uniqueness,self)
end
class Subthing
def initialize(uniqueness,master)
@u = uniqueness
@master = master
end
# Here I'm forwarding method calls
def one_thing
master.one_thing(self)
end
def four_things
master.four_things(self)
end
def many_things(times)
master.many_things(times,self)
end
end
end
m = Master.new(42)
s = m.make_a_sub("very")
s.one_thing === m.one_thing(s)
s.many_things(8) === m.many_things(8,s)
I hope you can see what's going on here. I would use method_missing, but I'm not sure how to cope with the possibility of some calls having arguments and some not (I can't really rearrange the order of the arguments to the Master methods either)
Thanks for reading!