防止在 url 助手中转义斜杠(特别是在使用 .send() 调用 url_helpers 时) [英] Prevent escaping slashes in url helpers (specifically when called using .send() to url_helpers)

查看:80
本文介绍了防止在 url 助手中转义斜杠(特别是在使用 .send() 调用 url_helpers 时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这个问题的标题很神秘,但问题是真实的,我刚刚将一个应用程序从 Rails 3 升级到 4 并遇到了以下问题(在 Ruby 2.0 和 2.1 上):

Perhaps the title of this question is cryptic, but the problem is real, I've just upgraded an application from Rails 3 to 4 and encountered the following issue (on both Ruby 2.0 and 2.1):

我有一个方法,它使用 send() 在循环中调用多个 url helper,如下所示:

I have a method which calls several url helpers in a loop, using send(), like this:

class Sitemap
  include Rails.application.routes.url_helpers
  #...
  # regions = [:city, :county, :zip]
  regions.each do |region|
    url_params = ... # [name, additional_id]
    send("#{region}_url", url_params)
  end

在 Rails 3 中,上面的结果是 http://example.com/cities/atlanta/2

In Rails 3 the above resulted in urls like http://example.com/cities/atlanta/2

在 Rails 4 中,我得到 http://example.com/cities/atlanta%2f2

In Rails 4 I get http://example.com/cities/atlanta%2f2

斜线让 CGI 转义,我不想要这个.我使用它为我的网站生成站点地图 XML,即使正斜杠被转义,它似乎也能工作,但它看起来很难看,我不知道它是否适用于所有机器人或客户端.

slash gets CGI escaped, I don't want this. I use it in generating sitemap XML for my site and it seems to work even if the forward slash is escaped, but it looks ugly and I don't know if it will work correctly for all bots or clients.

更新:经过一些调试,我发现 CGI 转义发生在 ActionDispatch::Journey::Visitors::Formatter 中的某处

UPDATE: after some debugging I've found out that the CGI escaping occurs somewhere in ActionDispatch::Journey::Visitors::Formatter

Router::Utils.escape_segment() # method call somewhere in 
ActionDispatch::Journey::Visitors::Formatter # during
Visitors::Formatter.new(path_options).accept(path.spec) # in
@set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE) # in a call to
ActionDispatch::Routing::RouteSet::Generator#generate

推荐答案

我能够解决生成 URL 时转义斜杠的问题,这是更改:

I was able to fix the issue with escaping slashes when generating the URL, here's the change:

# from:
send(region_url, url_params)
# to:
send(region_url, { id: url_params[0], market_id: url_params[1]})
# sometimes url_params is a one element array

关键是提供具有明确分配的键和值的参数散列.

The key is to provide a hash of parameters with explicitly assigned keys and values.

我使用发送从包含在我的模型中的 url_helpers 模块动态调用方法 (xxx_url).url_params 数组看起来像 ['some-slug', 12]

I use send to dynamically call method (xxx_url) from url_helpers module which is included in my model. url_params array looks like ['some-slug', 12]

这篇关于防止在 url 助手中转义斜杠(特别是在使用 .send() 调用 url_helpers 时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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