本文介绍了在引擎中使用观察者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个引擎,该引擎基本上用于我们所有的项目.

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

现在我要做的是向此引擎中的所有模型添加before_create回调.

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

现在我需要将其添加到应用程序中,但是当然在我的引擎中没有诸如application.rb这样的文件,因此我将其放置在了我的引擎中:

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)

推荐答案

在引擎中,您应该使用lib/[engine_name]/engine.rb

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.

这篇关于在引擎中使用观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 18:46