gpt4 book ai didi

Ruby 转发方法调用

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:32 25 4
gpt4 key购买 nike

我有一个生成子类实例的主类实例,这些子类需要将一些方法调用转发回主实例。

目前我的代码看起来像这样,但感觉我应该能够更有效地做同样的事情(也许使用 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)

我希望你能看到这里发生了什么。我会使用 method_missing,但我不确定如何处理某些调用有参数而有些没有的可能性(我也无法真正重新排列主方法的参数顺序)

感谢阅读!

最佳答案

支持委托(delegate)模式


代表


Delegate帮忙吗?它允许您将方法委托(delegate)给第二个类

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

Going a step further, the top level DelegateClass method allows you to easily setup delegation through class inheritance. This is considerably more flexible and thus probably the most common use for this library.

Finally, if you need full control over the delegation scheme, you can inherit from the abstract class Delegator and customize as needed. (If you find yourself needing this control, have a look at forwardable, also in the standard library. It may suit your needs better.)


可转发


还有 forwardable图书馆

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

关于Ruby 转发方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2942386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com