Encode HTML entities in helpers and views in Ruby on Rails

February 1, 2008

 
No Gravatar

Valid XHTML is good, manually encoding your HTML entities is bad! Why the encoding is not built into the framework, I don’t know, but a simple plugin makes it easy to accomplish such a task. Install this plugin and can will be blessed with encode_entities and decode_entities.

No big deal? Well…pay particular attention to your meta description and title tags. I personally think it is good practice to encode these fields just like you’d html_escape all user controllable strings.

Installation from command line:
script/plugin install http://svn.bountysource.com/leftbee-plugins/html_helpers
or via git (will only work in edge rails, 2.02)
script/plugin install git://github.com/tma/html_helpers.git

How to use it!

1
2
3
4
5
6
7
8
# this will encode a UTF-8 string with HTML entities
# returns "Check out my resumé"
<%= encode_entities("Check out my resumé") %>
 
 
# decode an encoded string
# returns "Check out my resumé"
<%= decode_entities("Check out my resum&Atilde;&copy;") %>
  • Joris,

    ERB's html_escape only handles &, ", .

    Here's the source from the link you provide:

    # File erb.rb, line 806
    def html_escape(s)
    s.to_s.gsub(/&/, "&").gsub(/\"/, """).gsub(/>/, ">").gsub(/</, "<")
    end
  • Why don't you just use ERB's built-in functionality?
    "html_escape" or simply "h"

    http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/...
  • Jonathan
    Thanks for the update, I'll adjust the post accordingly!
  • tma
    I got the permission to push the plugin on github, so you can use it as git submodule, if you like.

    http://github.com/tma/html_helpers
blog comments powered by Disqus