I need to override quite a few path helper methods in Ruby on Rails and call super from them. My standard approach would be:
path_helper.rb
def business_path(business)
if params[:city_id] == 2
moscow_business_path(business)
else
super
end
end
But I have a lot of these methods, so I want to define them dynamically like this:
%i[root businesses business ...].each do |path_method|
method_name = "#{path_method}_path"
old_method = method(method_name)
define_method(method_name) do |*args|
if params[:city_id] == 2
public_send("moscow_#{method_name}")
else
old_method.call(*args)
end
end
end
But I get this error:
/home/leemour/Ruby/burobiz/app/helpers/path_helper.rb:31:in `method': undefined method `root_path' for class `Module' (NameError)
from /home/leemour/Ruby/burobiz/app/helpers/path_helper.rb:31:in `block in <module:PathHelper>'
from /home/leemour/Ruby/burobiz/app/helpers/path_helper.rb:29:in `each'
from /home/leemour/Ruby/burobiz/app/helpers/path_helper.rb:29:in `<module:PathHelper>'
from /home/leemour/Ruby/burobiz/app/helpers/path_helper.rb:1:in `<top (required)>'
from /home/leemour/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.1.3/lib/active_support/dependencies.rb:476:in `load'
I guess helper modules haven't been included yet, so there is no original path helper method to capture with method(method_name)
. Then I guess I'd have to use self.included
hook but I couldn't figure it. How can I adjust this code to make it work? (I don't want to use eval).