Encode HTML entities in helpers and views in Ruby on Rails

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!

# 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;") %>

8 comments

  1. 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

  2. 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

  3. Thanks for the update, I’ll adjust the post accordingly!

  4. Thanks for the update, I’ll adjust the post accordingly!

  5. 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/classes/ERB/Util.html#M000658

  6. 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/classes/ERB/Util.html#M000658

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

  8. 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

Leave a comment