Call Ruby Forwarding Method

I have an instance of a master class that generates instances of a subclass, these subclasses should redirect some method calls back to the main instance.

At the moment, I have code that looks something like this, but it seems to me that I could do the same thing more efficiently (perhaps using the method_missing method?)

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 see what happens here. I would use the method_missing method, but I'm not sure how to deal with the possibility of some calls with arguments and some not (I can’t even reorder the order of the arguments for the Master methods)

Thank you for reading!

+4
source share
1 answer

Delegation Template Support


Delegation


Does Delegate help here? This allows you to delegate methods to the second class.

This library provides three different ways to delegate method calls to an object. The easiest to use is SimpleDelegator. Pass the object to the constructor, and all methods supported by the object will be delegated. This object can be changed later.

Going further, the top-level DelegateClass method allows you to easily configure delegation through class inheritance. This is a much more flexible and probably the most common use of this library.

Finally, if you need full control over the delegation scheme, you can inherit from the abstract class Delegator and configure it as needed. (If you need this control, look at the redirects, also in the standard library. This might suit you better.)


Available for shipment


There is also a forwardable library

This library allows you to delegate method calls to an object based on a method by method. You can use Forwardable to configure this delegation at the class level, or SingleForwardable to process it at the object level.

+6
source

Source: https://habr.com/ru/post/1311395/


All Articles