Using an observer within an Engine

2019-02-28 10:18发布

问题:

I've created an Engine which is basically used for all of our projects.

Now what I want to do is add a before_create callback to all of the models in this Engine.

After some searching I found out that an observer is the way to go.

So, I've created this observer:

# app/models/baco/auth/auth_observer

class Baco::Auth::AuthObserver < ActiveRecord::Observer

  def before_create( record )
    p record
  end

end

And now I need to add it to the application, but of course in my Engine there is no such file as application.rb, so I've placed it in my engine:

# lib/baco/auth/engine.rb

require 'rails'
require 'devise'

module Baco
  module Auth
    class Engine < Rails::Engine

      engine_name 'baco_auth'
      config.active_record.observers = :auth_observer

    end
  end
end

But I get the following error on starting the server:

.../.rvm/gems/ruby-1.9.3-p125/gems/activesupport-3.2.1/lib/active_support/inflector/methods.rb:229:in `block in constantize': uninitialized constant AuthObserver (NameError)

回答1:

In engines, instead of application.rb you should use lib/[engine_name]/engine.rb

Also, if you create observer inside an engine, you need to namespace it.