views:

485

answers:

3

I am using h helper method in Rails to encode/escape a string that has an apostrophe (') In my view I am using it like this

<%=h "Mike's computer" %>

My understanding is that the html when viewing the source should be Mike%27s computer but the html produced has an apostrophe in it, Mike's computer

Am I missing something obvious?

How do I get my desired result of Mike%27s computer?

Help is always appreciated.

+3  A: 

An apostrophe is a valid character in HTML. It is not encoded because it is not needed to be encoded.

Darin Dimitrov
@Darin Dimitrov, thank you for your reply. So in that case is gsub("'","%27") the only approach? or is there another way?
Anand
What you're looking for is URL-encoding, not HTML-encoding - Google led me to this: CGI::escape("Mike's Computer")
K Prime
Darin is telling you that no further action is required.
John Topley
@K Prime: Indeed Googling before posting this question also led me to CGI::escape , but was unsure of how to use it in a view, and thought there might be some other way of achieving the required output.
Anand
+1  A: 

If we look at the source code of the h method (it is an alias for html_escape), it is not that hard to just open the file and add the single quote (') to the HTML_ESCAPE constant in the file.

Below is the source code of the method with the location of the method in the file. Find the constant and and the quote in. You can even add more things inside as you want it.

HTML_ESCAPE = { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;' }

File actionpack/lib/action_view/template_handlers/erb.rb, line 17
17:     def html_escape(s)
18:       s.to_s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] }
19:     end

CAVEAT: This modification will affect all projects that uses the library.

OR an alternative will be to create a view helper method say in ApplicationHelper

def h_with_quote(s)
  HTML_ESCAPE = { "'" => "%27"}
  h(s).gsub(/[']/) {|special| HTML_ESCAPE[special]}
end

That approach should be safer.

SamChandra
Why would you monkey patch Rails to do something that isn't required?
John Topley
That is why I put a caveat and an alternative answer which is not a monkey patch.I think it is an advantage of open source that you can modify the source code to solve a problem. For this case, you have a point since the alternative can be used. Thanks for pointing that out.
SamChandra
+1  A: 

If you want to encode a URL, use u helper:

>> fer@:~/$ script/console
Loading development environment (Rails 2.3.8)
>> include ERB::Util
=> Object
>> h "Mike's computer"
=> "Mike's computer"
>> u "Mike's computer"
=> "Mike%27s%20computer"
>> 
FernandoFabreti