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}&foo=bar&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}&foo=bar&baz=some_other_stuff" -%>
<a href="<%= redirect_href =>">Foo</a>
Run Code Online (Sandbox Code Playgroud)
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
Vik*_*rón 30
可以从任何地方使用,ruby std lib的一部分.
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?
| 归档时间: |
|
| 查看次数: |
54021 次 |
| 最近记录: |