Rails: @controller 从哪里来?
Rails: where does the @controller come from?
我正在开发一个旧插件 "menu_helper"(遗留代码使用它)。
https://github.com/pluginaweek/menu_helper
本馆正门如下,
module PluginAWeek
module MenuHelper
def menu_bar(options = {}, html_options = {}, &block)
puts @controller.class
MenuBar.new(@controller, options, html_options, &block).html
end
end
end
ActionController::Base.class_eval do
helper PluginAWeek::MenuHelper
end
代码在 rails 2.3.5 中没有问题,但在 4.2.6 中失败。
当我输入 @controller.class 时,在 2.3.5 中,它将始终 return 使用此库的当前控制器,但在 4.2.6 中它将是 NillClass。
那么这个@controller 是从哪里来的呢? 4.2.6如何修改才能生效
注1:要使用这个,我只需要调用
html = menu_bar(options,:id => 'menuid')
没有传入任何控制器。
注意 2:我目前正在 运行 进行控制器测试。
谢谢。
首先,我不会使用过去 5 年未维护且主构建当前失败的 gem。我会尝试找到一个维护良好的替代方案,或者如果 gem 足够小,我会自己重做。
话虽如此,menu_helper
似乎使用了这个变量:https://github.com/pluginaweek/menu_helper/blob/master/lib/menu_helper/menu.rb#L51
如果你想让它工作,做一个before_action
,用当前控制器实例化这个变量:
before_action :set_legacy_controller
def set_legacy_controller
@controller = controller
end
我正在开发一个旧插件 "menu_helper"(遗留代码使用它)。
https://github.com/pluginaweek/menu_helper
本馆正门如下,
module PluginAWeek
module MenuHelper
def menu_bar(options = {}, html_options = {}, &block)
puts @controller.class
MenuBar.new(@controller, options, html_options, &block).html
end
end
end
ActionController::Base.class_eval do
helper PluginAWeek::MenuHelper
end
代码在 rails 2.3.5 中没有问题,但在 4.2.6 中失败。
当我输入 @controller.class 时,在 2.3.5 中,它将始终 return 使用此库的当前控制器,但在 4.2.6 中它将是 NillClass。
那么这个@controller 是从哪里来的呢? 4.2.6如何修改才能生效
注1:要使用这个,我只需要调用
html = menu_bar(options,:id => 'menuid')
没有传入任何控制器。
注意 2:我目前正在 运行 进行控制器测试。
谢谢。
首先,我不会使用过去 5 年未维护且主构建当前失败的 gem。我会尝试找到一个维护良好的替代方案,或者如果 gem 足够小,我会自己重做。
话虽如此,menu_helper
似乎使用了这个变量:https://github.com/pluginaweek/menu_helper/blob/master/lib/menu_helper/menu.rb#L51
如果你想让它工作,做一个before_action
,用当前控制器实例化这个变量:
before_action :set_legacy_controller
def set_legacy_controller
@controller = controller
end