You want to display data that might contain HTML or JavaScript without making browsers render it as HTML or interpret the JavaScript. This is especially important when displaying data entered by users.
Pass a string of data into the h() helper function to escape its HTML entities. That is, instead of this:
<%= @data %>
Write this:
<%=h @data %>
The h() helper function converts the following characters into their HTML entity equivalents: ampersand (&), double quote ("), left angle bracket (<), and right angle bracket (>).
You won find the definition for the h() helper function anywhere in the Rails source code, because its a shortcut for ERbs built-in helper function html_escape().
JavaScript is deployed within HTML tags like , so escaping an HTML string will neutralize any JavaScript in the HTML. However, sometimes you need to escape just the JavaScript in a string. Rails adds a helper function called escape_javascript() that you can use. This function doesn do much: it just turns line breaks into the string " ", and adds backslashes before single and double quotes. This is handy when you want to use arbitrary data in your own JavaScript code:
Strings
Numbers
Date and Time
Arrays
Hashes
Files and Directories
Code Blocks and Iteration
Objects and Classes8
Modules and Namespaces
Reflection and Metaprogramming
XML and HTML
Graphics and Other File Formats
Databases and Persistence
Internet Services
Web Development Ruby on Rails
Web Services and Distributed Programming
Testing, Debugging, Optimizing, and Documenting
Packaging and Distributing Software
Automating Tasks with Rake
Multitasking and Multithreading
User Interface
Extending Ruby with Other Languages
System Administration