How do I URL-escape a string in Rails?

后端 未结 4 1534
心在旅途
心在旅途 2020-12-08 08:52

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

\">Foo

相关标签:
4条回答
  • 2020-12-08 09:38

    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?

    0 讨论(0)
  • 2020-12-08 09:46

    CGI.escape will do it:

    <% redirect_href = "/redirect?#{CGI.escape target}&amp;foo=bar&amp;baz=some_other_stuff" -%>
    <a href="<%= redirect_href =>">Foo</a>
    
    0 讨论(0)
  • 2020-12-08 09:58

    Rails (activesupport) defines Hash#to_param (aliased to 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).

    Hash#to_param also accepts optional namespace parameter:

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

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

    0 讨论(0)
  • 2020-12-08 09:58

    ERB::Util.url_encode

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

    0 讨论(0)
提交回复
热议问题