Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I URL-escape a string in Rails?

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?

like image 655
Josh Glover Avatar asked May 19 '11 11:05

Josh Glover


People also ask

How do you escape a parameter in a URL?

URL escape codes for characters that must be escaped lists the characters that must be escaped in URLs. If you must escape a character in a string literal, you must use the dollar sign ($) instead of percent (%); for example, use query=title%20EQ%20"$3CMy title$3E" instead of query=title%20EQ%20'%3CMy title%3E' .

What does CGI escape do?

CGI. escape is for escaping a URL value in the query string. All characters that don't fall into the ALPHA, DIGIT, '_', '-', '. ' and ' ' character set are escaped.


2 Answers

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> 
like image 124
Josh Glover Avatar answered Sep 21 '22 07:09

Josh Glover


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

like image 37
Ernest Avatar answered Sep 25 '22 07:09

Ernest