Ruby-on-rails 如何在 Rails 中对字符串进行 URL 转义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6057972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:10:40  来源:igfitidea点击:

How do I URL-escape a string in Rails?

ruby-on-railsurlescaping

提问by Josh Glover

If I'm in an RHTML view in Rails, it is easy to URL-escape something:

如果我在 Rails 的 RHTML 视图中,很容易对某些内容进行 URL 转义:

<a href="/redirect?href=<%=u target %>">Foo</a>

How do I do this in a string? I'd like to do something like this:

我如何在字符串中执行此操作?我想做这样的事情:

<% redirect_href = "/redirect?#{url_escape target}&amp;foo=bar&amp;baz=some_other_stuff" -%>
<a href="<%= redirect_href =>">Foo</a>

This must be trivial, right?

这一定是微不足道的,对吧?

回答by Josh Glover

CGI.escapewill do it:

CGI.escape会这样做:

<% redirect_href = "/redirect?#{CGI.escape target}&amp;foo=bar&amp;baz=some_other_stuff" -%>
<a href="<%= redirect_href =>">Foo</a>

回答by Ernest

Rails (activesupport) defines Hash#to_param(aliased to Hash#to_query):

Rails ( activesupport) 定义Hash#to_param(别名为Hash#to_query):

 {foo: 'asd asdf', bar: '"<#$dfs'}.to_param
 # => "bar=%22%3C%23%24dfs&foo=asd+asdf"

It's worth noting that it sorts query keys (for HTTP caching).

值得注意的是,它对查询键进行排序(用于 HTTP 缓存)。

Hash#to_paramalso accepts optional namespace parameter:

Hash#to_param还接受可选的命名空间参数:

{name: 'David', nationality: 'Danish'}.to_param('user')
# => "user[name]=David&user[nationality]=Danish"

http://api.rubyonrails.org/classes/Hash.html#method-i-to_param

http://api.rubyonrails.org/classes/Hash.html#method-i-to_param

回答by Viktor Trón

ERB::Util.url_encode

ERB::Util.url_encode

can be used from anywhere, part of ruby std lib.

可以从任何地方使用,是 ruby​​ std lib 的一部分。

回答by thekingoftruth

Use either CGI::escapeor ERB::Util.url_encodebut not URI.encode.

使用CGI::escapeor ERB::Util.url_encodebut not URI.encode

URI.escapehas been deprecated circa Ruby 1.9.2: What's the difference between URI.escape and CGI.escape?

URI.escape在 Ruby 1.9.2 左右已被弃用:URI.escape 和 CGI​​.escape 之间有什么区别?