2

谁能指导我通过正确的方式将现有的 Helper 添加到以前不包含此 Helper 的扩展控制器中。

例如,我在 timelog_controller_patch.rb 中扩展timelog_controller.rb控制器。然后,我尝试添加帮助程序 Queries,它带来了一些我想在我的补丁中使用的功能。

如果我在我的补丁(我的时间日志扩展控件)中添加助手,我总是会得到同样的错误:

错误:未初始化的常量 Rails::Plugin::TimelogControllerPatch (NameError)

这是我如何做的一个例子:

module TimelogControllerPatch       
    def self.included(base)
        base.send(:include, InstanceMethods)
        base.class_eval do
          alias_method_chain :index, :filters
        end
    end
    module InstanceMethods
        # Here, I include helper like this (I've noticed how the other controllers do it)
        helper :queries
        include QueriesHelper

        def index_with_filters
            # ...
            # do stuff
            # ...
        end
    end # module
end # module patch

但是,当我在原始控制器中包含相同的助手时,一切正常(当然,这不是正确的方法)。

有人可以告诉我我做错了什么吗?

提前致谢 :)

4

2 回答 2

4

需要在控制器的类上调用该helper方法,方法是将其放入无法正确运行的模块中。这将起作用:

module TimelogControllerPatch       
    def self.included(base)
        base.send(:include, InstanceMethods)
        base.class_eval do
          alias_method_chain :index, :filters
          # 
          # Anything you type in here is just like typing directly in the core
          # source files and will be run when the controller class is loaded.
          # 
          helper :queries
          include QueriesHelper

        end
    end
    module InstanceMethods
        def index_with_filters
            # ...
            # do stuff
            # ...
        end
    end # module
end # module patch

随意查看我在 Github 上的任何插件,我的大部分补丁都在lib/plugin_name/patches. 我知道我在那里有一个可以添加帮助器的工具,但我现在找不到。https://github.com/edavis10

PS不要忘记也需要您的补丁。如果它不在您lib的插件目录中,请使用相对路径。

埃里克·戴维斯

于 2012-01-13T22:03:24.373 回答
0

或者,如果您不想使用补丁来执行此操作:

Rails.configuration.to_prepare do
  TimelogController.send(:helper, :queries)
end
于 2013-10-18T13:42:18.873 回答