访问 routes.rb 中的 URL 助手 [英] Accessing URL helpers in routes.rb

查看:58
本文介绍了访问 routes.rb 中的 URL 助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用以下几行重定向路由中的路径:

I would like to redirect a path in routes using the following lines:

get 'privacy_policy', :controller => :pages, :as => 'privacy_policy'
get 'privacypolicy.php' => redirect(privacy_policy_url)

这样/privacypolicy.php 就会被重定向到它上面定义的正确页面.

So that /privacypolicy.php gets redirected to the correct page defined right above it.

但是,它抛出以下错误:

However, it's throwing the following error:

undefined local variable or method `privacy_policy_url'

所以我猜你不能在 routes.rb 中使用 URL 助手.有没有办法在路由文件中使用 URL helper,这样做是否可取?

So I'm guessing one cannot use URL helpers in routes.rb. Is there a way to use URL helpers in the route file, and is it advisable to do so?

推荐答案

我知道我在这里有点晚了,但是这个问题是谷歌搜索在 routes.rb 中使用 url_helpers"时最热门的问题之一,我最初在我偶然发现这个问题时找到了它,所以我想分享我的解决方案.

I know I'm a little late here, but this question is one of the top hits when googling "use url_helpers in routes.rb", and I initially found it when I had stumbled upon this problem, so I'd like to share my solution.

正如@martinjlowm 在他的回答中提到的,在绘制新路由时不能使用 URL 助手.但是, 有一种方法可以使用 URL 帮助程序定义重定向路由规则.事情是,ActionDispatch::Routing::Redirection#redirect 可以使用一个块(或一个 #call-able),它是 稍后(当用户点击路由时)用两个参数调用的,paramsrequest,返回一个新的路由,一个字符串.并且因为路由是在那个时刻正确绘制的,所以在块内调用 URL helper 是完全有效的!

As @martinjlowm mentioned in his answer, one cannot use URL helpers when drawing new routes. However, there is one way to define a redirecting route rule using URL helpers. The thing is, ActionDispatch::Routing::Redirection#redirect can take a block (or a #call-able), which is later (when the user hits the route) invoked with two parameters, params and request, to return a new route, a string. And because the routes are properly drawn at that moment, it is completely valid to call URL helpers inside the block!

get 'privacypolicy.php', to: redirect { |_params, _request|
  Rails.application.routes.url_helpers.privacy_policy_path
}

此外,我们可以使用 Ruby 元编程工具来添加一些糖:

Furthermore, we can employ Ruby metaprogramming facilities to add some sugar:

class UrlHelpersRedirector
  def self.method_missing(method, *args, **kwargs) # rubocop:disable Style/MethodMissing
    new(method, args, kwargs)
  end

  def initialize(url_helper, args, kwargs)
    @url_helper = url_helper
    @args = args
    @kwargs = kwargs
  end

  def call(_params, _request)
    url_helpers.public_send(@url_helper, *@args, **@kwargs)
  end

  private

  def url_helpers
    Rails.application.routes.url_helpers
  end
end

# ...

Rails.application.routes.draw do
  get 'privacypolicy.php', to: redirect(UrlHelperRedirector.privacy_policy_path)    
end

这篇关于访问 routes.rb 中的 URL 助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆