【发布时间】:2015-10-28 09:16:27
【问题描述】:
我正在编写一个包含一个主应用程序和一个可安装引擎的 Rails 应用程序,但我遇到了一些让我发疯的问题。
Rails 在从引擎控制器调用主应用控制器中定义的函数时随机发出 NoMethodError。
到目前为止,我已经在主应用程序中定义了一个控制器,引擎中的控制器从该控制器继承。下面是目录结构的总结,是“my_plugin”引擎的目录(代码也附在下面)。
我注意到,当 WEBrick 运行时,如果我只是“触摸”bar_controller.rb 文件(即不加修改地保存它),那么一切都会开始正常运行。似乎 Rails 有时在启动期间无法正确加载父类,并且触摸文件会使其重新加载所有内容(抱歉,我不知道 Rails 内部是如何工作的)。
我做错了什么?
app
|- controllers
|- foo_controller.rb
...
plugins
| - my_plugin
| - app
| - controllers
| - my_plugin
| - application_controller.rb
| - bar_controller.rb
foo_controller.rb中的代码是:
class FooController < ActionController::Base
protect_from_forgery with: :null_session
private
def my_function
#...
end
end
另一方面,我的插件application_controller.rb 中的代码是:
module MyPlugin
#Inherit from main's app FooController
class ApplicationController < ::FooController
end
end
最后,我的插件bar_controller.rb中的代码是:
module MyPlugin
class BarController < ApplicationController
def index
#####################################################
# The statement below issues NoMethodError until
# I touch this file while WEBrick is running.
#####################################################
my_function
end
end
end
编辑
我注意到如果我在插件的application_controller.rb 中定义my_function(见下文)并且不从FooController 继承,问题仍然存在。所以看起来这个问题与应用程序类的继承无关。
module MyPlugin
class ApplicationController < ActionController::Base
private
def my_function
#...
end
end
end
【问题讨论】: