【问题标题】:Why ActiveSupport core extension not added as module?为什么 ActiveSupport 核心扩展没有作为模块添加?
【发布时间】:2020-12-12 17:16:00
【问题描述】:

我在阅读 ActiveSupport core_ext 源码,看到它直接打开并扩展核心 ruby​​ 类,例如:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/string/conversions.rb .这不会让我们更难知道某些方法是来自 activesupport 还是实际上由 ruby​​ 本身提供(例如通过Method#owner)?

为什么它不使用诸如前置/包含模块之类的东西来赋予其附加功能?例如:

module StringConversionExtension
  def to_time
    # some implementation
  end
end

String.prepend(StringExtension)

现在的实施是否有任何历史/性能原因?

【问题讨论】:

  • 只想指出Method#source_location 会告诉你它是否来自 ActiveSupport,即使owner 不是。
  • 我忘了!但是问题仍然存在,为什么 ActiveSupport 不通过前置/包含模块来扩展核心类?

标签: ruby-on-rails ruby activesupport


【解决方案1】:

为什么它不使用诸如前置/包含模块之类的东西来赋予其附加功能?例如:

可能:

  • 尽量减少 Rails 中的代码量(因为您提出的方法有点冗长),或者
  • 尽量减少现有以及核心类中的方法/常量/模块的数量,因为在您提出的方法中,核心 String 类将具有新方法并且它现在将包括StringExtensions 模块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2020-02-27
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多