问题
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