Update: ActionView has been refactored in Rails 2.0.2, making Erubis’ Rails helper, and the “Create an Erubis Initializer” section of this article, obsolete. See the comments for a Rails 2.0.2 compatible initializer. Thanks for the tip, Jason!
Erubis is a drop in replacement for Erb. Among its many features are a few notable improvements in terms of speed and security (it optionally supports auto-html escaping).
Sample Erubis Syntax:1 2 3 4 5 |
# Erubis with auto HTML escaping enabled: Hello, <%= current_user.name %> # equivalent to h(current_user.name) <%== render :partial => 'user' %> |
Installing Eribus:
1. Install the gem
gem install erubis |
2. Create an Erubis initializer
app/config/initializers/erubis.rb1 2 3 4 5 6 7 8 9 10 11 |
# Via http://www.kuwata-lab.com/erubis/users-guide.05.html#topics-rails # The above link also references an optional patch that can be applied. require 'erubis/helpers/rails_helper' # These are optional settings: Erubis::Helpers::RailsHelper.init_properties = { :escape => true, :escapefunc => 'h' } # Erubis::Helpers::RailsHelper.engine_class = Erubis::Eruby # or Erubis::FastEruby # Erubis::Helpers::RailsHelper.show_src = false # Erubis::Helpers::RailsHelper.preprocessing = true |
3. Create custom rescue templates
The default Rails debug views need to be slightly modified to support Eribus. This problem only pops up in a few spots, but Eribus doesn’t handle inline statements:
1 2 3 4 5 6 7 |
# Default Rails sample: <%= request.parameters["controller"].capitalize if request.parameters["controller"] %> # Erubis compatible rewrite: <% if request.parameters["controller"] %> <%= request.parameters["controller"].capitalize %> <% end %> |
If auto-escaping is enabled, all instances of <%= need to be replaced with <%== and <%=h replaced with <%=.
Step 1: Download these auto escaped, Eribus-friendly templates and put them in app/views/rescues
Step 2: Redefine the rescues path to point to the modified templates:
controllers/application.rb1 2 3 4 |
# For Erubis compatible debug templates def rescues_path(template_name) "#{view_paths.first}/rescues/#{template_name}.erb" end |
Using Erubis
Auto escaped Erubis vs Erb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Erubis doesn't handle inline parsing well. # While in Erb, this would work: # <%=h status = current_user.status if returning_user? %> # It needs to be broken out in Erubis: <% if returning_user? %> <%= current_user.status %> # Auto HTML escaped <% end %> Here's a list of your friends, <%= current_user.first_name %> # Auto-escaped <ul> <%== render :partial => 'friend', :collection => @friends %> # Not escaped </ul> <p><%== submit_tag "Add a friend", :class => "button" %></p> # Not escaped <% end %> |
- Erubis doesn’t handle inline statements well
- If auto escape is enabled, use the <%== operator when rendering partials and helpers
- Update app/views/layout templates
