dennismonsewicz
dennismonsewicz

Reputation: 25542

Rails 3.1: UrlEncode issues with periods (.)

I have a site where when a user searches for an artist, song or album and click search, the search results are displayed. The individual search terms are then set to be clickable, meaning each use their own paths (or routes) to generate links.

The issue I keep running into is with random weird characters showing up in some of the artists, songs or album names (such as periods (.)). Is there anyway to url encode these?

Here is my current code:

<% artists[0..5].each do |art| %>
                        <li><span><strong><%= link_to "#{art}", artist_path(CGI::escape(art)) %></strong></span></li>
                <% end %>

Upvotes: 2

Views: 790

Answers (1)

rickypai
rickypai

Reputation: 4016

Assume you have an album name called "slash@^[]/=hi?qqq=123"

encoded = URI.escape str_to_be_encoded

encoded = URI.escape(str_to_be_encoded, Regexp.new("[^#{URI::PATTERN::UNRESERVED.gsub('.','')}]"))

The first one would encode to

"slash@%5E[]/=hi?qqq=123"

The second would encode to

"slash%40%5E%5B%5D%2F%3Dhi%3Fqqq%3D123"

What happens is that most url encoding methods would not escape characters that it thinks it part of a value url, so symbols like equal and question mark are not escaped.

The second method tells the escape function to also escape url-legal characters. So you get a better encoded string.

You can then append it to your url like

"http://localhost:3000/albums/1-#{encoded}"

Hope this helps.

Upvotes: 2

Related Questions