为什么初始化程序中定义的方法会间歇性地引发 'not defined' 错误,该错误可通过重新启动服务器来解决?

Why do methods defined in an initializer intermittently raise a 'not defined' error which is resolved by restarting the server?

我将 PaperTrail 4.1 与 Rails 4.2.

一起使用

我在初始化程序中定义了几个自定义方法(参见:How to add a method to the versions model of Paper_trail?

#config/initializers/paper_trail.rb
PaperTrail::Rails::Engine.eager_load!
module PaperTrail
  class Version < ActiveRecord::Base
    scope :scoped,      lambda { #selects some records }
    def custom_method
      #does some stuff
    end
  end
end

在开发环境中,我经常得到一个 method not defined error 用于此初始化程序中定义的方法/范围。

重启服务器解决问题。

为什么这些方法是 'lost' 到 Rails?

这个问题是否也会出现在生产或其他环境中?

我可以采取哪些步骤来查找此问题的原因?

对于到达此处的任何其他人,显然这是 PaperTrail 的一个已知问题

来自https://github.com/airblade/paper_trail/pull/492

Now the paper_trail source get's reloaded in the development environment when saving a file which means the class gets discarded from the cache and rebuild from the paper_trail sources. The initializer is not interpreted again since they are one time only, no module_eval, no abstract class -> exceptions.

并且 gem 的最新版本中包含了修复:https://github.com/airblade/paper_trail/pull/557

本质上,不再建议使用初始化器为 PaperTrail 添加自定义方法,而是使用继承自 PaperTrail 的模型(更适合 AR)。

# app/models/paper_trail/version.rb
module PaperTrail
  class Version < ActiveRecord::Base
    include PaperTrail::VersionConcern
    # my custom methods
  end
end