The Mysterious h Function

At some point in your Ruby on Rails life, you may discover you need to print a few HTML tags on screen with their angle-brackets. Or maybe you need to list emails, quotation marks, and other strange characters in their properly-escaped HTML characters. Or, even more important, you capture user input in your application and output-it, but need to protect yourself against cross-site scripting–things like users entering .

Or maybe you just heard about this really nifty function called “h”.

What is the h function, and how can it help you?

The h function is really CGI.escapeHTML in disguise. This function encodes a string, such that the string appears properly on-screen in it’s existing form–so things like < and > become encoded, tabs become &nbsp, and so on.

How do you use it? Simply write h(stringVariable) in your code, and it works! (Note that if you’re in a view file, that’s all; if you’re in a model file, you may need to fully qualify it by typing CGI.escapeHTML(someString).

And it’s a good idea to wrap in any user-inputted fields–such as comments, a login, etc.–in h() function calls, because it protects you from cross-site scripting!

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Comments are closed.