Rails Engine中的观察者 [英] Observers in Rails Engines

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

问题描述

我正在尝试在Rails引擎中创建一个观察者,该观察者将在我的主应用程序中观察模型.

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

我的观察者(在app/models/my_engine/my_observer.rb中)是

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

为了注册观察者,我已将引擎(在lib/my_engine/engine.rb中)修改为

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)

但是,这与在引擎内使用观察者的答案完全相同

我在命名空间上做错了吗?这是我想要达到的最佳方法吗?

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

推荐答案

我最终发现了问题所在.

I eventually figured out the problem.

现实是您无法在engine.rb文件中提供实际的类,因为在Rails运行配置时,尚未加载任何这些东西.这就是为什么为普通观察者提供符号而不是类的原因.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆