繁体   English   中英

从 Engine in Rails 3.x 应用程序重新打开模型和控制器

[英]Reopen models and controllers from Engine in Rails 3.x app

我想通过在 Rails 应用程序中重新打开它们来扩展 Engine 中的模型和控制器。 问题是应用程序启动时它们没有加载。 我知道有一些解决方案,比如Rails 引擎扩展功能以及如何覆盖主应用程序中的 Rails 3 引擎模型和控制器? ,但我怀疑这是由于导轨的加载顺序造成的,应该有一些巧妙的解决方案。

然后我遇到了这个解决方案:

config.railties_order = [Blog::Engine, :main_app, :all]

但是,Engine 中的模型和控制器被加载,而不是 rails 中的模型和控制器。 只是想知道以前是否有人做过这项工作?

您可以通过让主 Rails 应用程序控制器继承自 Rails Engine 来重新打开 controller 类。 这不需要config.railties_order来让控制器工作,

#/app/controllers/answer_sheets_controller.rb
require YourCustomEngine::Engine.root.join('app', 'controllers', 'your_custom_engine', 'answer_sheets_controller')

class AnswerSheetsController < YourCustomEngine::AnswerSheetsController

由于某种原因,此策略不适用于模型。

我的解决方案:

# === in engine
class EngineNameSpace::Blog
  # logic goes here
end

class Blog < EngineNameSpace::Blog
  # no codes should go here
end

# === in app
# If I need to extend the Blog class, I will code as below instead of reopenning the class
class Blog < EngineNameSpace::Blog
  # do something
end

解释:

如果引擎类与父应用程序中的文件名/路径相同,Rails 会阻止引擎类加载。请参阅http://www.cowboycoded.com/2011/02/06/making-the-case-for-rails -3-引擎/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM