为什么人们大多包装 I18n.t 方法而不是委托?

Why people mostly wrap I18n.t method instead of delegating?

我看到很多例子

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

很少

delegate :t, to: I18n

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

Why people tend to not use it?

嗯,一个原因(正如@BroiSatse 所提到的)是人们根本不了解这种技术。

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

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

所以选择是基于我们想要传达的信息。是的,我们的应用程序中有两种形式的 I18n.t 委派 :)

例如:

# 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