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 <script>alert(users[0].password);</script>.

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!

Tags: , ,     Posted in Development

Rate this article:
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

Related Content


Leave a Reply