【问题标题】:Extending Rails 4 engine models with concerns关注扩展 Rails 4 引擎模型
【发布时间】:2016-12-06 15:26:09
【问题描述】:

我正在尝试通过应用初始化程序扩展引擎 1 的模型,并关注引擎 2 的问题,但我得到了一些奇怪的行为,这就是我所得到的:

关注

module Engine2
  module Concerns
    module MyConcern

      extend ActiveSupport::Concern

      included do
        puts "Concern included!"
      end

      def jump
        puts 'Jumping!!!!'
      end
    end
  end
end

初始化器

require 'engine2/my_concern'

module Engine1
  class Member
    include Engine2::Concerns::MyConcern
  end
end

当我启动应用程序时,我在控制台中看到Concern included! 消息,Member 类可以调用方法jump,但是一旦我更改主机应用程序中的任何代码,我得到以下错误:

NoMethodError (undefined method 'jump' for #<Engine1::Member:0x007fe7533b4f10>)

我必须重新加载服务器,然后它再次正常工作,直到我在主机应用程序中进行另一次更改,然后它再次抛出错误,为什么会发生这种情况以及如何避免它?

是否有更好的地方我应该执行类打开以包含关注点而不是初始化程序?

【问题讨论】:

    标签: ruby-on-rails rails-engines activesupport-concern


    【解决方案1】:

    所以我终于弄明白了,基本上发生的情况是,在开发模式下,每个模型都会在每次代码更改时重新加载,但初始化程序只在服务器启动时运行一次,所以一旦控制器中的代码发生更改,模型已重新加载,但不再包含问题,因此中断。

    我通过将初始化程序的代码移动到application.rb 中的to_prepare 块来解决它。

    对于那些不知道的人,to_prepare 添加了一个准备回调,它将在开发模式中的每个请求之前运行,或者在生产中的第一个请求之前运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多