如何URL转义Rails中的字符串?

Jos*_*ver 54 url escaping ruby-on-rails

如果我在Rails中的RHTML视图中,很容易URL转义:

<a href="/redirect?href=<%=u target %>">Foo</a>
Run Code Online (Sandbox Code Playgroud)

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

<% redirect_href = "/redirect?#{url_escape target}&amp;foo=bar&amp;baz=some_other_stuff" -%>
<a href="<%= redirect_href =>">Foo</a>
Run Code Online (Sandbox Code Playgroud)

这一定是微不足道的吧?

Jos*_*ver 73

CGI.escape会这样做:

<% redirect_href = "/redirect?#{CGI.escape target}&amp;foo=bar&amp;baz=some_other_stuff" -%>
<a href="<%= redirect_href =>">Foo</a>
Run Code Online (Sandbox Code Playgroud)

  • `CGI.escape`不是最好的东西,因为它将空格编码为'+',它被弃用,并不总是在另一侧正确解析.例如,如果你有Rails路由"/ my-path /:query",其中查询包含'+',它将在路由解析后保持为'+'.为了使它更好地工作,使用`ERB :: Util.u(string)`,它将空格转义为"%20". (7认同)

Ern*_*est 65

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

 {foo: 'asd asdf', bar: '"<#$dfs'}.to_param
 # => "bar=%22%3C%23%24dfs&foo=asd+asdf"
Run Code Online (Sandbox Code Playgroud)

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

Hash#to_param 还接受可选的namespace参数:

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

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

  • 似乎它正在将空格变成 `+` 而不是 `%20` `&gt;&gt; {y: "blah blah"}.to_query` 输出 `"y=blah+blah"` (3认同)

Vik*_*rón 30

ERB :: Util.url_encode

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

  • @HenrikN 我当时的评论是正确的 - 后来(2013年2月10日11:49)答案被[更改](https://stackoverflow.com/posts/14787553/revisions)。 (4认同)

the*_*uth 9

Use either CGI::escape or ERB::Util.url_encode but not URI.encode.

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