Add existing helper in an extended controller (Redmine Plugin Dev)
-
16-04-2021 - |
Question
Can anyone guide me through the right way to add an existing Helper into an extended controller which previously did not contain this helper.
For example, I have extended the timelog_controller.rb controller in timelog_controller_patch.rb. Then, I tried to add the helper Queries, which brings some functionality that I want to use in my patch.
If I add the helper in my patch (my timelog extended control), I always get the same error:
Error: uninitialized constant Rails:: Plugin:: TimelogControllerPatch (NameError)
Here is an example of how I have done:
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
However, when I include the same helper in the original controller, everything works fine (of course, this is not the right way).
Could someone tell me what am I doing wrong?
Thanks in advance :)
Solution
The helper
method needs to be called on the controller's class, by putting it into a module it isn't getting run correctly. This will work:
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
Feel free to look at any of my plugins on Github, most of my patches will be in lib/plugin_name/patches
. I know I have one there that adds a helper but I can't find it right now. https://github.com/edavis10
P.S. don't forget to require your patch too. If it's not in your lib
directory of your plugin, use the relative path.
Eric Davis
OTHER TIPS
Alternatively if you don't want to do it with a patch:
Rails.configuration.to_prepare do
TimelogController.send(:helper, :queries)
end