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

时间:2011-05-19 11:32:54

标签: ruby-on-rails url escaping

如果我在Rails中的RHTML视图中,很容易通过网址转义:

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

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

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

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

4 个答案:

答案 0 :(得分:72)

CGI.escape会这样做:

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

答案 1 :(得分:64)

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

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

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

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

答案 2 :(得分:27)

ERB::Util.url_encode

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

答案 3 :(得分:8)

使用CGI::escapeERB::Util.url_encode但不使用URI.encode

URI.escape已被弃用,大约是Ruby 1.9.2:What's the difference between URI.escape and CGI.escape?