gpt4 book ai didi

ruby-on-rails - 为什么人们大多包装 I18n.t 方法而不是委托(delegate)?

转载 作者:太空宇宙 更新时间:2023-11-03 17:47:39 25 4
gpt4 key购买 nike

我看到很多例子

def t(*args)
I18n.t(*args)
end

很少

delegate :t, to: I18n

老实说,第二种解决方案在语义上更好。为什么人们往往不使用它?

最佳答案

Why people tend to not use it?

好吧,一个原因(如@BroiSatse 所述)是人们根本不了解这种技术。

从字节码的角度来看,差别不大。 delegate 生成大致相同的方法,并进行一些额外的安全检查(respond_to? 等)

在我们的团队中,我们有这样的规则:delegate 应该用于向外部 调用者提示方法正在被转发到其他对象。因此,它应该仅用于“缩短”委托(delegate)方法的内部调用。也就是说,如果一个方法不是从外部调用的,则不要对其使用 delegate,自己编写转发。

所以选择是基于我们想要传达的信息。是的,我们在我们的应用程序中对 I18n.t 进行了两种形式的委托(delegate) :)

例如:

# use `delegate`, method is called from outside
class User
has_one :address

delegate :country, to: :address
end

<%= user.country %>


# only internal callers, do not use `delegate`
class Exporter
# delegate :export, to: :handler
def call
handler.export
end

private

def handler
return something_with_export_method
end
end

关于ruby-on-rails - 为什么人们大多包装 I18n.t 方法而不是委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32091962/

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