Josh Glover Josh Glover - 4 months ago 28
Ruby Question

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?

Answer

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>
Comments