在 Rails-4.2 中,当初始化期间将方法 'create' 和 'update' 添加到 AR::Base 时?

In Rails-4.2 when during initialisation do the methods 'create' and 'update' get added to AR::Base?

问题:我们有许多用于审计目的的自定义列。它们在功能上类似于 Rails 时间戳,但包含不同的数据。我们之前实现了一个初始化程序,它使用 alias_method_chain 拦截 AR::Base 的创建和更新方法,执行必要的检查,并在插入或更新行之前立即填充任何找到的审计列。

但是,从 Rails-4 开始,在加载初始化程序时 AR::Base 中不存在创建和更新方法。所以这种方法失败了。

要使用现有技术,我需要准确了解这两种方法何时添加到 AR::Base 以及如何在之后的某个时间包含我们的拦截模块。但是,我并不拘泥于现有的解决方案,如果有更好的方法,我愿意实施。

理想情况下,我只想做一些实际方法代码近似于以下内容的事情:

module HLLAuditStamps

  def create
    set_audit_attributes
    super
  end

  def update
    set_audit_attributes
    super
  end

private
  def set_audit_attributes
    . . .
  end
end  

class AR::Base
  include HLLAuditStamps
end

这个或者类似的东西可以做吗?我们试图避免的是必须添加代码来处理每个模型。

我最终使用了在 提出的问题作为我的回答模板。这在大多数方面与下面提出的相同。

你能做类似的事情吗:

module HLLAuditStamps
  extend ActiveSupport::Concern

  included do
    before_save :set_audit_attributes
  end

  private

  def set_audit_attributes
    # . . .
  end
end

ActiveRecord::Base.class_eval { include HLLAuditStamps }

这只会在每个 AR 实例上使用标准 before_save 回调。