从父应用程序重新打开 Rails 3 引擎类 [英] Reopening Rails 3 engine classes from parent app

查看:25
本文介绍了从父应用程序重新打开 Rails 3 引擎类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就目前而言,您无法通过简单地在父应用程序的 /app 目录中添加相同的类来重新打开引擎的 /app 目录中包含的引擎类.例如:

As it stands now, you can't reopen Engine classes contained within the engine's /app directory by simply adding the same class in the parent app's /app dir. For example:

/my_engine/app/controllers/users_controller.rb
/my_app/app/controllers/users_controller.rb

如果父应用程序中有同名文件,来自 my_engine 的文件甚至不会加载.更多细节在这里:

The file from my_engine will not even load if there is a file with the same name in the parent app. More details here:

http://www.cowboycoded.com/2011/02/28/why-you-cant-reopen-rails-3-engine-classes-from-the-parent-app/

我正在寻找一种解决方法,允许我在与父应用程序相同的路径中删除相同的文件名/类,然后重新打开而不是覆盖类.也许我错过了一些明显的东西.我可以使用使用 class_eval 的单独文件(不同的文件名)来完成这项工作,但我对这个解决方案并不满意.关于此问题的优雅解决方案有什么想法吗?

I am looking for a workaround that will allow me to drop the same filename/class in the same path as the parent app, and reopen instead of overwrite the class. Maybe I am missing something obvious. I am able to make this work with a separate file (different filename) that uses class_eval, but I am not really happy with that solution. Any ideas on an elegant solution for this?

我也想知道这个限制背后是否有原因,或者只是因为 rails 加载文件的方式(见包含的链接)而不是故意的.在我看来,改变引擎的加载行为以允许以这种方式重新打开类将是 Rails 的一个很好的特性.我知道一开始我很困惑,我相信其他开发者也会遇到这个问题.

I am also wondering if there is a reason behind this restriction, or is it just a result of how rails loads files (see included link) and not intentional. It seems to me that changing the load behavior of engines to allow reopening classes in this manner would be a good feature in rails. I know it confused me at first, and I am sure other developers will struggle with this problem as well.

推荐答案

在 Rails 3.2.2/Ruby 1.9 中开启重新加载插件,然后在重新打开插件之前使用 require_dependency 要求引擎中的类类和添加功能.这甚至在开发环境中也有效(即类重新加载).

In Rails 3.2.2 / Ruby 1.9 turn on reloading of plugins, then require the class in the engine using require_dependency before reopening the class and adding functionality. This works even in development environment (i.e class reloading).

# development.rb
config.reload_plugins = true 

# app/controllers/my_engine/documents_controller.rb
require_dependency MyEngine::Engine.root.join('app', 'controllers', 'my_engine', 'documents_controller').to_s

module MyEngine
  class DocumentsController
    def show
      render :text => 'different'
    end
  end
end

这篇关于从父应用程序重新打开 Rails 3 引擎类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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