How do I URL-escape a string in Rails? How do I URL-escape a string in Rails? ruby-on-rails ruby-on-rails

How do I URL-escape a string in Rails?


CGI.escape will do it:

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


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


ERB::Util.url_encode

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