How do I URL-escape a string in Rails?

Ruby on-RailsUrlEscaping

Ruby on-Rails Problem Overview


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

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

How do I do this in a string? I'd like to do something like this:

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

This must be trivial, right?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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>

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

ERB::Util.url_encode

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

Solution 4 - Ruby on-Rails

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

URI.escape has been deprecated circa Ruby 1.9.2: https://stackoverflow.com/questions/2824126/whats-the-difference-between-uri-escape-and-cgi-escape

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJosh GloverView Question on Stackoverflow
Solution 1 - Ruby on-RailsJosh GloverView Answer on Stackoverflow
Solution 2 - Ruby on-RailsErnestView Answer on Stackoverflow
Solution 3 - Ruby on-RailsViktor TrónView Answer on Stackoverflow
Solution 4 - Ruby on-RailsthekingoftruthView Answer on Stackoverflow