Observers in Rails Engines

£可爱£侵袭症+ 提交于 2019-12-10 22:59:28

问题


I'm trying to create an observer in my Rails engine that will observe a model in my main application.

My observer (in app/models/my_engine/my_observer.rb) is,

module MyEngine
  class MyObserver < ActiveRecord::Observer
    observe AppModel

    def after_create
      # code to run when callback is observed
    end
  end
end

In order to register the observer, I've modified my engine (in lib/my_engine/engine.rb) to be,

module MyEngine
  class Engine < ::Rails::Engine
    isolate_namespace MyEngine

    config.active_record.observers = MyEngine::MyObserver
  end
end

However, when I tried to start the server I get the following error,

... in `<class:Engine>': uninitialized constant MyEngine::MyObserver (NameError)

Yet this is exactly the same as the accepted answer to Using an observer within an Engine

Am I doing something wrong with the namespacing? Is this the best method for what I'm trying to achieve?


回答1:


I eventually figured out the problem.

The reality is that you can't supply the actual class in the engine.rb file because at the time Rails runs the config, none of these things have been loaded yet. This is why for normal observers we supply symbols rather than classes.

However there is no way to supply a symbol that includes the namespace. Instead, we supply the namespace and class in a string.

module MyEngine
  class Engine < ::Rails::Engine
    isolate_namespace MyEngine

    config.active_record.observers = 'MyEngine::MyObserver'
  end
end


来源:https://stackoverflow.com/questions/17803809/observers-in-rails-engines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!