3

我正試圖開發一個插件/寶石,目前觀察多個模型。理想情況下,觀察者應自動只有一個單身方法實例化......爲多個模型動態實例化一個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,但沒有運氣。

所以,它當時是:

觀察員的定義,但不知道要觀察哪些車型。 模型被定義並標記自己被觀察,但觀察者已被觀察到。

有沒有一種方法可以延遲觀察者的加載,直到模型被定義或可以有人想到更好的方法來解決這個問題?

回答

-1

@gavin:Rails3中應用程序初始化的結構發生了變化 - 這可能是您的問題。

您何時/如何包括ClassMethods模塊?如果您在Rails3中,並且如果您向$ ROOT/config/environment.rb添加了「require'observe_me'」,那麼您會看到您描述的(錯誤)行爲。

如果是這樣,請改爲創建$ ROOT/config/initializers/my_extensions.rb並在其中粘貼「require ...」。

+0

這對我沒有用 – Dinedal 2011-05-17 22:06:32