gpt4 book ai didi

ruby-on-rails - 使用 define_method 覆盖 Rails 中的路径助手

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:50 24 4
gpt4 key购买 nike

我需要重写 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 钩子(Hook),但我想不出来。我如何调整此代码以使其工作? (我不想使用 eval)。

最佳答案

您是否尝试过使用 Rails.application.routes.url_helpers 方法,而不是尝试使用 Kernel.method

%i[...].each do |path_method|
define_method("#{path_method}_path") do |*args|
if params[:city_id] == 2
public_send("moscow_#{path_method}_path", *args)
else
Rails.application.routes.url_helpers.public_send("#{path_method}_path", *arsg)
end
end
end

关于ruby-on-rails - 使用 define_method 覆盖 Rails 中的路径助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50494898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com