Anand Shah
Anand Shah

Reputation: 14913

Rails html encoding

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.

Upvotes: 1

Views: 2455

Answers (3)

FernandoFabreti
FernandoFabreti

Reputation: 1903

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

Upvotes: 5

Samuel Chandra
Samuel Chandra

Reputation: 1185

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.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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

Upvotes: 5

Related Questions