3

我目前正在尝试开发一个观察多个模型的插件/宝石。理想情况下,观察者应该只用一个单例方法自动实例化......

class MyModel < ActiveRecord::Base

  # a class method like this will tell the observer to observe this model
    observe_me

end

我最初的方法是定义包含在 AR 基础中的类方法:

module ClassMethods

  def observe_me
    @observe_me = true
  end

  def should_observe_me?
    @observe_me
  end
end
ActiveRecord::Base.extend(ClassMethods)

然后使用它来检测在观察者中观察哪些模型:

class MyObserver < ActiveRecord::Observer

  # this should observe all models where should_observe_me? #=> true
  observe ActiveRecord::Base.descendants.select { |m| m.try(:should_observe_me?) }.map(&:model_name)

end

我遇到的问题是在定义模型之前正在加载观察者,因此 ActiveRecord 没有后代,并且 MyObserver 不知道要观察哪些模型。

我的下一次尝试是破解 ActiveRecord::Base.observers 和 ActiveRecord::Base.instantiate_observers 但没有运气。

所以,就目前而言:

观察者已定义,但不知道要观察哪些模型。模型被定义并标记自己要被观察,但观察者已经被观察到。

有没有办法可以将观察者的加载延迟到定义模型之后,或者有人可以想出更好的方法来解决这个问题?

4

1 回答 1

-1

@gavin:Rails3 中应用程序初始化的结构发生了变化——这可能是你的问题。

您何时/如何包含 ClassMethods 模块?如果您在 Rails3 中,并且如果您在 $ROOT/config/environment.rb 中添加了“require 'observe_me'”,那么您会看到您描述的(错误)行为。

如果是这样,请创建 $ROOT/config/initializers/my_extensions.rb 并在其中粘贴“require ...”。

于 2011-01-29T00:02:49.807 回答