我正试图开发一个插件/宝石,目前观察多个模型。理想情况下,观察者应自动只有一个单身方法实例化......为多个模型动态实例化一个ActiveRecord Observer
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
,我快到的问题是,被定义模型前,观察员被加载,所以ActiveRe绳子没有后代,MyObserver不知道要观察哪些模型。
我的下一个尝试是破解ActiveRecord :: Base.observers和ActiveRecord :: Base.instantiate_observers,但没有运气。
所以,它当时是:
观察员的定义,但不知道要观察哪些车型。 模型被定义并标记自己被观察,但观察者已被观察到。
有没有一种方法可以延迟观察者的加载,直到模型被定义或可以有人想到更好的方法来解决这个问题?
这对我没有用 – Dinedal 2011-05-17 22:06:32