Dynamically creating an ActiveRecord Observer instance for multiple models

I am trying to develop a / gem plugin at the moment that is watching several models. Ideally, an observer should be automatically created using just one method ...

class MyModel < ActiveRecord::Base

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

end

My initial approach was to define the class methods included in the AR base:

module ClassMethods

  def observe_me
    @observe_me = true
  end

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

And then use this to determine which models should be observed in Observer:

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

The problem I am facing is that the observer boots up before defining the models, so ActiveRecord has no descendants, and MyObserver does not know which models should be observed.

My next attempt was to hack ActiveRecord :: Base.observers and ActiveRecord :: Base.instantiate_observers, but no luck.

So, how is it now:

, , . , .

, - ?

+3
1

@gavin: Rails3 - .

/ ClassMethods? Rails3, "require_ observ_me" $ROOT/config/environment.rb, (mis), .

, $ROOT/config/initializers/my_extensions.rb "require...".

-1

Source: https://habr.com/ru/post/1779219/


All Articles