gpt4 book ai didi

ruby - 直通方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:17:57 27 4
gpt4 key购买 nike

有谁知道提供传递方法来提供类似以下但添加了 DRY 的方法吗?

class Cover

@some_class = SomeClass.new

def some_method
@some_class.some_method
end

end

理想情况下,我想把它弄干成这样:

class Cover

@some_class = SomeClass.new
passthrough @some_class.some_method

end

如果没有猴子修补我自己的生活,人们还有什么吗?

干杯,

罗亚

最佳答案

支持委托(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/2230645/

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