【发布时间】:2018-05-23 18:14:16
【问题描述】:
我需要在 Ruby on Rails 中重写很多路径辅助方法并从它们中调用 super。我的标准方法是:
path_helper.rb
def business_path(business)
if params[:city_id] == 2
moscow_business_path(business)
else
super
end
end
但是我有很多这些方法,所以我想像这样动态定义它们:
%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
但我收到此错误:
/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'
我猜还没有包含辅助模块,所以没有原始路径辅助方法可以用method(method_name) 捕获。然后我想我必须使用self.included 钩子,但我想不通。如何调整此代码以使其正常工作? (我不想使用 eval)。
【问题讨论】:
-
看看:stackoverflow.com/a/4471202/3982562。特别是“方法包装”部分。
标签: ruby-on-rails ruby