简体   繁体   English

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

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

I want to extend the models and controllers from Engine by reopening them in the Rails app.我想通过在 Rails 应用程序中重新打开它们来扩展 Engine 中的模型和控制器。 The problem is they are not loaded when the app starts.问题是应用程序启动时它们没有加载。 I know there are some solutions for this like Rails engines extending functionality and how to override rails 3 engine models and controllers in the main application?我知道有一些解决方案,比如Rails 引擎扩展功能以及如何覆盖主应用程序中的 Rails 3 引擎模型和控制器? , but I suspect this is due to the loading sequence of rails, and there should be some neat solution. ,但我怀疑这是由于导轨的加载顺序造成的,应该有一些巧妙的解决方案。

Then I come across with this solution:然后我遇到了这个解决方案:

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

However, models and controllers in Engine are loaded, but not the ones in rails.但是,Engine 中的模型和控制器被加载,而不是 rails 中的模型和控制器。 Just wondering if anyone made this work before?只是想知道以前是否有人做过这项工作?

You can reopen the controller classes by having the main Rails application controllers inherit from a Rails Engine.您可以通过让主 Rails 应用程序控制器继承自 Rails Engine 来重新打开 controller 类。 This did not require the config.railties_order in order to get the controllers working,这不需要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

From some reason, this strategy is not working for the models.由于某种原因,此策略不适用于模型。

My Solution:我的解决方案:

# === 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

Explain:解释:

Rails blocks the engine classes from loading if they are the same file name/path as something in the parent app., see http://www.cowboycoded.com/2011/02/06/making-the-case-for-rails-3-engines/如果引擎类与父应用程序中的文件名/路径相同,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