21 Oct
Posted by ProCOM
on October 21, 2007 – 1:34 pm - 1,297 views
If you're new here, you may want to subscribe to my RSS feed. So that you can read the latest updates about Web2.0 tools, Making Money Online, Tips in SEO, Ajax and many more. Thanks for visiting ProgramimiCOM!
In this conclusion to a two-part article, you’ll learn how to drag and drop slides in our example slideshow to modify it, and how to filter by category. This article is excerpted from chapter six of the book Ruby on Rails: Up and Running, written by Bruce A. Tate and Curt Hibbs (O’Reilly, 2006; ISBN: 0596101325). Copyright © 2006 O’Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O’Reilly Media.
Drag and Drop Everything (Almost Everything)
We have already displayed a list of thumbnails of all photos that are in the slideshow and enabled the user to drag them around to rearrange their order in the slideshow. Now let’s add a second list of thumbnails, showing all photos that are not being used in the slideshow.
We’ll let the user add a photo to the slideshow by dragging it from the list of unused photos and dropping it onto the slideshow thumbnails. Similarly, we can enable the user to remove photos from the slideshow by dragging its thumbnail from the slideshow and dropping on the unused photos list. Finally, we’ll allow the user to filter the unused photos list by category.
As you might expect, we can accomplish all that in a very small amount of code. We will add a mere 58 lines of Ruby code to the models and controllers, 47 lines to the view templates, and 16 lines to our CSS stylesheet! Figure 6-4 gives you a preview of how this is going to look when we’re done.
Figure 6-4. Preview of drag-and-drop slideshow editing
Let’s start by updating the slideshow’s edit template. Edit photos/app/views/slideshows/edit.rhtml to look like this:
<h1>Editing slideshow</h1>
<div id=’slideshow-contents’>
<p style=’text-align: center;’><b>Slideshow Photos</b></p>
<div id=’slideshow-thumbs’>
<%= render :partial => ’show_slides_draggable’ %>
</div>
</div>
<div id=’slideshow-photo-picker’>
<p style=’text-align: center;’><b>Unused Photos</b></p>
<div id=’slideshow-photos’>
<%= render :partial => ‘photo_picker’ %>
</div>
</div>
<div id=’slideshow-attributes’>
<p><%= link_to ‘Play this Slideshow’, :action => ’show’, :id => @slideshow %></p>
<div style=’border: thin solid; padding-left: 1em;’>
<p style=’text-align: center;’><b>Attributes</b></p>
<%= start_form_tag :action => ‘update’, :id => @slideshow %>
<%= render :partial => ‘form’ %>
<%= submit_tag ‘Save Attributes’ %>
<%= end_form_tag %>
</div>
<p>
<b>Hint:</b> Drag and drop photos between the
two lists to add and remove photos from the
slideshow. Drag photos within the slideshow to
rearrange their order.
</p>
</div>
<%= drop_receiving_element(”slideshow-contents”,
:update => “slideshow-thumbs”,
:url => {:action => “add_photo” },
:accept => “photos”,
:droponempty => “true”,
:loading => visual_effect(:fade),
:complete => visual_effect(:highlight, ’sortable_thumbs’)
) %>
This file has been almost entirely rewritten, so there are no marked-as-changed lines. You can see that I have laid out this edit page into three sections:
<div id=’slideshow-contents’> . . . </div>
<div id=’slideshow-photo-picker’> . . . </div>
<div id=’slideshow-attributes’> . . . </div>
Only the slideshow-photo-picker is new. It shows the list of unused photos that can be added to the slideshow. We will set up the CSS stylesheet to display these sections side-by-side as you saw them in Figure 6-4.
slideshow-contents is rendered by the partial template show_slides_draggable,
slideshow-photo-picker is rendered by the partial template photo_picker, and slideshow-attributes is mostly rendered by the form partial template that was generated from the scaffolding. I say “mostly” because I added a few things inline around the rendering of form.
Finally, notice two Ajax related helpers: drop_receiving_element and observe_field. We’ll come back to these in a little bit after we have discussed some prerequisite details.
Now, make these changes to photos/app/controllers/slideshows_controller.rb, replacing the edit method and creating the unused_photos method:
def edit
@slideshow = Slideshow.find(params[:id])
session[:slideshow] = @slideshow
@photos = unused_photos(@slideshow)
end
def unused_photos(slideshow)
all_photos = Photo.find(:all)
candidates = []
for photo in all_photos
in_slideshow = false
for slide in slideshow.slides
if slide.photo.thumbnail === photo.thumbnail
in_slideshow = true
break
end
end
candidates << photo if not in_slideshow
end
return candidates
end
The purpose of this code is to retrieve all the data needed by the edit.rhtml view template:
@slideshow = Slideshow.find(params[:id])
The id of the slideshow that you want to edit is passed in the request parameters from the browser. Here you retrieve that id and read that slideshow from the database, which you store in the instance variable @slideshow to make it available to the view template.
session[:slideshow] = @slideshow
Ajax actions requests will be coming in as the user makes changes, and you need to know what slideshow to change. This line saves a reference to the slideshow in the session hash. I’m using a key value of :slideshow to save and retrieve this from the session, but that value is arbitrary and could have been any unique identifier.
@photos = unused_photos(@slideshow)
This line calls the new method unused_photos to retrieve a list of all photos that are not in the slideshow; it then saves that list in @photos.
def unused_photos(slideshow)
This method returns a list of photos that are not in the slideshow. The logic should be self-explanatory. First, create an empty array (candidates = []), and then iterate through the list of all photos, adding them to the array (candidates << photo) if they are not already in the slideshow. The technique used here is grossly inefficient, but it will suffice for our purposes.
We still need to create the photo_picker template that generates the HTML to display all the photos that can still be added to a slideshow, so go ahead and create the file photos/app/views/slideshows/_photo_picker.rhtml with this in it:
<% for photo in @photos %>
<%= image_tag(”photos/#{photo.thumbnail}”,
:style => “vertical-align: middle”,
:id => “photo_#{photo.id}”,
:class => “photos”) %>
<%= draggable_element “photo_#{photo.id}”, :revert => true %>
<% end %>
This template iterates through the list of photos in @photos. For each photo, it uses the image_tag helper to create an HTML image tag and the draggable_element helper to generate the JavaScript code that makes it draggable. You can see that the first parameter of draggable_element matches the value of the id attribute (:id => “photo_#{photo.id}”) on the image tag. The draggable_element helper expects the id of the HTML element that it should make draggable, followed by zero or more options. The single option used here (:revert => true) says to move the element back to its original position after it is dropped.
But where can these draggable images be dropped? Recall that at the end of the slideshow’s edit.rthtml template we had:
<%= drop_receiving_element(”slideshow-contents”,
:update => “slideshow-thumbs”,
:url => {:action => “add_photo” },
:accept => “photos”,
:droponempty => “true”,
:loading => visual_effect(:fade),
:complete => visual_effect(:highlight, ’sortable_thumbs’)
) %>
Just like the draggable_element helper, the drop_receiving_element helper expects the ID of the HTML element onto which you can drop something that was declared as draggable. The remaining parameters are options that given as name/value pairs (the order is not important). These options are doing a lot, so let’s go through them one at a time:
:update => “slideshow-thumbs”
This gives the ID of the HTML element that should be updated when a photo is dropped on our slideshow-contents div. The :position and :url options say how, and with what, that HTML element should be updated. When the :position option is omitted (as it is here), the HTML returned from the server replaces the target elements HTML. The :position option says that the returned HTML should be inserted into target element, instead of replacing it. The value :position can be specified as :before, :top, :bottom, and :after.
:url => {:action => “add_photo” }
This option constructs the URL that is sent to the server (via a background Ajax request) when a photo is dropped (you’ve seen this before). This executes the add_photo method in the current controller (the SlideshowsController). The add_ photo action adds the dropped photo to the slideshow and returns an HTML fragment that will replace the existing HTML in the target element, which, as you will see, is a rerendering of the slideshow’s contents, which now include the added photo.
:accept => “photos”
Without this option, you could drop any draggable element here. However, this line says that only HTML elements that have the class attribute “photos” can be dropped here. Remember that in our photo picker template we gave each photo class attribute of “photos”.
:droponempty => “true”
This option says that the user can drop photos here even if the target is completely empty.
:loading => visual_effect(:fade)
:complete => visual_effect(:highlight, ’sortable_thumbs’)
:loading and :complete (plus a few more events) specify client-side JavaScript event handlers that are executed at specific points in the progress of the Ajax request. In both cases, we are displaying a visual effect that gives the user positive feedback. The :loading event occurs when the browser begins loading the response, and the :complete event occurs when its all finished. The code specifies that the dropped photo will fade until it becomes invisible. It also highlights the target area on which the photo was dropped.
Adding a Dropped Photo
Now we need to create the add_photo method to actually add a dropped photo to the slideshow. Edit photos/app/controllers/slideshows_controller.rb, and add this:
def add_photo
slideshow_id = session[:slideshow].id
photo_id = params[:id].split(”_”)[1]
slide = Slide.new()
slide.photo_id = photo_id
slide.slideshow_id = slideshow_id
if !slide.save
flash[:notice] = ‘Error: unable to add photo.’
end
@slideshow = Slideshow.find(slideshow_id)
session[:slideshow] = @slideshow
render_partial ’show_slides_draggable’
end
Let’s walk through this code:
slideshow_id = session[:slideshow].id
This line retrieves the current slideshow from the session hash and gets the slideshow’s id.
photo_id = params[:id].split(”_”)[1]
The id attribute of the dropped photo get passed as the :id parameter. If you recall from the photo_picker template, we set those ids to values such as “photo_1″ and “photo_19″, so the remainder of this line of code splits the string on the underscore, grabs the second half, and assigns it to photo_id.
The next five lines create a new slide, assign to it the photo id and the slideshow id, and then save it to the database.
Finally, we render and return the show_slides_draggable partial, after setting @slideshow to the current slideshow (which is needed by the partial template).
All that code handles dragging new photos to add to the slideshow. Now we just need to add a little more code to implement dragging a photo from the slideshow to the unused photos list as an intuitive way to remove photos from the slideshow.
The displayed list of photos in the slideshow are already draggable because we made them into a sortable list. The only problem with the current implementation is that the photos can be dragged vertically only. They need to be dragged both vertically for reordering and horizontally to the unused photos column.
We can drag the photos only vertically because the default option for a sortable list is :constraint => ‘vertical’. Fortunately, you can change this by editing the file photos/app/views/slideshows/_show_slides_draggable.rhtml and changing the call to the sortable_element helper to add this :constraint option:
<%= sortable_element(’sortable_thumbs’,
:url => {:action => ‘update_slide_order’},
:constraint => ”) %>
Now you can drag those photos anywhere. But you still need to make the unused photos list into a drop receiver that uses Ajax to remove the dropped photo from the slideshow.
To do so, edit photos/app/views/slideshows/edit.rhtml, and add this at the end:
<%= drop_receiving_element(”slideshow-photo-picker”,
:update => “slideshow-photos”,
:url => {:action => “remove_slide” },
:accept => “slides”,
:droponempty => “true”,
:loading => visual_effect(:fade),
:complete => visual_effect(:highlight, ’slideshow-photos’)
) %>
This code is almost identical to the other drop_receiving_element we used. The difference is that the target is the slideshow-photo-picker, and the action taken on a drop is to call the remove_slide method. Also, notice that you can drop only “slides” here (that is, HTML elements with a class attribute of slides). If you go back and take a look at how we defined the partial template photos/app/views/ slideshows/_show_slides_draggable.rhtml, you will see that we did, indeed, make each item in the sortable list a slide.
Add the remove_slide method to photos/app/controllers/slideshows_controller.rb:
def remove_slide
slideshow_id = session[:slideshow].id
slide_id = params[:id].split(”_”)[1]
Slide.delete(slide_id)
@slideshow = Slideshow.find(slideshow_id)
session[:slideshow] = @slideshow
@photos = unused_photos(@slideshow)
render_partial ‘photo_picker’
end
In this code, you get the id of slide you want to remove, and then delete it from the slide database table. Remember, this action does not delete the photo from the database. The slide data says what photos are in a given slideshow, and deleting an entry from the slide table removes that slide from its slideshow. Finally, you render the HTML for the photo picker, which now includes the removed slide.
I’ll bet you’re anxious to see all this in action. All you need to do is to update the style sheet and then try it out. Edit photos/public/stylesheets/slideshows.css, and add the following:
#slideshow-photo-picker {
float: left;
width: 10em;
text-align: center;
border-right: thin solid #bbb;
padding: 0.50em;
padding-bottom: 10em;
}
img.thumbnail {
border: 2px solid black;
margin-bottom: 1em;
}
img.photos {
border: 2px solid black;
margin-bottom: 1em;
}
Whew! That’s it: try it now!
The first thing you’ll notice is that the Unused Photos section is empty (see Figure 6-5). That’s because all the photos are currently in the slideshow. Just drag a few of the slides out of the slideshow and drop them into the Unused Photos column; then you’ll have something more like Figure 6-6.
Filtering by Category
Displaying all unused photos might seem acceptable right now, but we have only nine photos. If there were 900, it would quickly become unusable. So, our final feature in this chapter will be to display only the unused photos in a particular category.
The first thing to do in our controller is get a list of all categories that can populate the drop-down selection box. Edit photos/app/controllers/slideshows_controller.rb, and add this line to the end of the edit method:
@all_categories = Category.find(:all, :order=>”name”)
This line retrieves a list of categories that can populate a drop-down selection box that the user will use to display only those unused photos that are in the selected category.
Figure 6-5. Drag and drop add and remov
Now, edit photos/app/views/slideshows/edit.rhtml, and add this right after the ‘Play this Slideshow’ line:
<p>
<label for=”category_id”>Filter “Unused Photos” on this Category</label><br/>
<%= collection_select(:category, :id, @all_categories, :id, :long_name) %>
<%= observe_field(:category_id,
:frequency => 2.0,
:update => ’slideshow-photos’,
:url => { :action => ‘change_filter’},
:with => ‘category_id’ ) %>
</p>
The collection_select helper is normally used inside an HTML form, but here we are using it because it conveniently knows how to display a collection in a drop-down box. It will never be submitted as part of a form.
As shown, the observe_field helper checks the category drop-down box for changes every two seconds. When a change is detected, an Ajax request is fired off to the change_filter method, which returns new HTML (that has been appropriately
filtered) to replace the slideshow-photos section.
Figure 6-6. Some unused photos
The Category model class automatically shows a collection of all photos that are in a particular category. However, we need to get a collection of photos that are in a given category and in all of its child categories.
Edit photos/app/models/category.rb, and add this method:
def photos_including_child_categories
result = photos.clone
children.each do |c|
c.photos_including_child_categories.each {|p|
result << p if not result.include? p}
end
result
end
This method recursively collects a list of all photos in its own category and all of its child categories. You can use this in to get the list of unused photos to display.
In the meantime, edit photos/app/controllers/slideshows_controller.rb to add the change_filter method:
def change_filter
slideshow_id = session[:slideshow].id
category_id = params[:category_id] || 1
session[:category_id] = category_id
@slideshow = Slideshow.find(slideshow_id)
session[:slideshow] = @slideshow
@photos = unused_photos(@slideshow)
render_partial ‘photo_picker’
end
This method stores the chosen category id in the session hash, retrieves a new list of unused photos, and then renders the photo_picker. Notice the bold code line in the previous code. This line tries to retrieve the category id from the request parameters. If there aren’t any parameters, params[:category_id] returns nil, and the || operator returns the rightmost argument (”1″ in this case).
Also, in this slideshow controller, we need to update the method that retrieves the unused photos to pay attention to the category setting. Do so by editing the unused_ photos method; then replace the line all_photos=Photo.find(:all) with the following:
category_id = session[:category_id] || 1
session[:category_id] = category_id
category = Category.find(category_id)
all_photos = category.photos_including_child_categories
We’re done; we’ve added category filtering! Fire up your browser, and try it (you may need to assign some categories to some unused photos). Now it looks like Figure 6-7.
Figure 6-7. Filtering on categories
We’ve come a long way in a very short time. With fewer than 200 lines of code, we’ve added drag-and-drop capability to add and reorder slides. We’ve also added the core capability to actually show a slideshow. Ajax made our application much easier to use and more attractive. Next, we’ll look into testing this application.
—
by O’Reilly Media
20 Oct
Posted by ProCOM
on October 20, 2007 – 1:23 pm - 1,371 views
In this first article in a two-part series, you will learn how Ruby on Rails implements Ajax. We will use the specific example of a slideshow to demonstrate our points. This article is excerpted from chapter six of the book Ruby on Rails: Up and Running, written by Bruce A. Tate and Curt Hibbs (O’Reilly, 2006; ISBN: 0596101325). Copyright © 2006 O’Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O’Reilly Media.
Ajax is one of the most important emerging trends in web applications. Web sites like Google Maps and Gmail dramatically demonstrate that web applications do not have to be slow, clunky, page-at-a-time web forms. Ajax techniques can reclaim some of the fluidity and responsiveness that was lost when we moved from desktop applications to web applications.
Ajax (which stands for the cryptic “Asynchronous JavaScript and XML”) is a technique for building web pages that are more interactive, exciting, and dynamic. Ajax is asynchronous: JavaScript libraries can communicate with the server at any time, and the web page need not be frozen while waiting for a response. Ajax uses JavaScript on the browser, any language on the server, and XML to specify messages.
When you use this emerging technique, a web page can communicate with the server at any time, updating only those portions of the display that need it. Users experience more responsive web pages, with immediate feedback. Even though using Ajax techniques usually requires significantly more sophisticated design and implementation skills, the benefits to the end user are so great that Ajax-enabled web applications will soon become the rule, not the exception. Fortunately, Rails makes Ajax so simple that, for typical cases, using Ajax is almost as easy as not using it.
How Rails Implements Ajax
Rails has a simple, consistent model for how it implements Ajax operations. Once the browser has rendered and displayed the initial web page, different user actions cause it to display a new web page (like any traditional web application) or trigger an Ajax operation:
Some trigger fires
This trigger could be the user clicking on a button or link, the user making changes to the data on a form or in a field, or just a periodic trigger (based on a timer).
The web client calls the server
A JavaScript method, XMLHttpRequest, sends data associated with the trigger to an action handler on the server. The data might be the ID of a checkbox, the text in an entry field, or a whole form.
The server does something
The server-side action handler–a Rails controller action (for our purposes)–does something with the data and returns an HTML fragment to the web client.
The client receives the response
The client-side JavaScript, which Rails creates automatically, receives the HTML fragment and uses it to update a specified part of the current pages HTML, often the content of a <div> tag.
These steps are the simplest way to use Ajax in a Rails application, but with a little extra work, you can have the server return any kind of data in response to an Ajax request, and you can create custom JavaScript in the browser to perform more involved interactions. We’ll stick to HTML fragments in this chapter.
Rails uses the Prototype and script.aculo.us JavaScript libraries to implement browser support for Ajax. You can use these libraries independently of Rails, but with their seamless integration with Rails, you probably wont want to. Throughout this chapter, we’ll exploit the Ajax and special-effects capabilities that come with Rails to implement missing features in our Photo Share application.
Playing a Slideshow
Let’s see what happens when we try to play a slideshow. Browse to http://127.0.0.1: 3000/slideshows/list, and click the Play link for our only slideshow. As you can see in Figure 6-1, this URL invokes the show action on the slideshow controller, but the action is still using the scaffold code.
We need to change this page to actually “play” the slideshow by sequentially displaying the pictures contained in the slideshow. To do this, we will initially display the first picture in the slideshow; then, once every two seconds, we’ll make an Ajax call to get and display the next picture.
The controller sets up all the slides in a slideshow for playback. You need to start @slideshow with the current slideshow set to play. You also need to put the current slide (initially, 0) and the whole slideshow into a holding area called the session, so you won’t have to read from the database each time you play a new slide. Edit the slideshows controller (app/controllers/slideshows_controller.rb), and modify the show method to look like this:
def show
@slideshow = Slideshow.find(params[:id])
session[:slideshow] = @slideshow
session[:slide_index] = 0
Figure 6-1. Playing a slideshow that still uses scaffolding
@slide = @slideshow.slides[0]
end
Every two seconds in this code, the browser sends an Ajax request to get the next slide. You can’t use instance variables to keep track of where you are in the slideshow because instance variables exist only until you finish processing the current request. Use the Rails-provided session object instead, which is persistent across requests. Let’s look at this code in a little more detail.
session[:slideshow] = @slideshow stores a reference to the current slideshow in the session hash at the key :slideshow. We do the same thing with the index of the current slide that is being played. We initially set the slide_index to zero to point to the first slide, and our Ajax request increments the index by one as it displays each slide. We can retrieve these values from the session hash during the Ajax requests for the next slide.
Now, edit the view template (app/views/slideshows/show.rhtml) to look like this:
<p><i><%= @slideshow.name %></i></p>
<div id=”slides”>
<%= render :partial => “show_slide” %>
</div>
<%= periodically_call_remote :update => ’slides’,
:url => { :action => :show_slide },
:frequency => 2.0 %>
This RHTML template contains three things: a title line, the div that displays the current slide, and a magic Ajax incantation that we will now pick apart.
The periodically_call_remote Rails helper function creates JavaScript that periodically sends a request to the server and uses the HTML fragment that is returned to replace the content of the update target. In this case, the update target is an HTML element with an ID of ’slides’, which is a <div> tag. The returned HTML fragment replaces the contents of this <div> tag. The URL that makes the request is constructed to ensure that it will be routed to the show_slide method of the current controller (the slideshows controller). Finally, the frequency parameter makes the call once every two seconds. All Ajax help functions take their parameters in key/value pairs, so you can list the parameters in any order.
We need to display each slide as it comes back to the client; Rails uses a partial HTML template to do this work. To create the partial view template, place the following contents in a new file called app/views/slideshows/_show_slide.rhtml:
<%= image_tag “photos/#{@slide.photo.filename}” %>
<p><%= @slide.photo.filename %></p>
And its controller method in app/controllers/slideshows_controller.rb:
def show_slide
@slideshow = session[:slideshow]
session[:slide_index] += 1
@slide = @slideshow.slides[session[:slide_index]]
if @slide == nil
session[:slide_index] = 0
@slide = @slideshow.slides[0]
end
render :partial => “show_slide”
end
This method retrieves the slideshow information from the session, moves to the next slide (or back to the beginning if at the end), and then explicitly renders the partial view template show_slide. You need to render a partial view or render with the option :render_layout => false . Otherwise, Rails tries to render a full template, including layout. As our page already has a layout, simply render a partial template, consisting of an image tag for the slide, and its name.
Finally, you need to update your standard layout template to include script tags for the Prototype JavaScript library because the client-side JavaScript code that Rails creates for you uses them, so in app/views/layouts/standard.rhtml, insert this line immediately after the title tags:
<%= javascript_include_tag ‘prototype’, ‘effects’, ‘dragdrop’ %>
This line includes three JavaScript files that are shipped with Rails: prototype.js and two Script.aculos.us files, effects.js and dragdrop.js. We will use these last two shortly.
Now show a slideshow by loading slideshows/list and clicking Show, and you will see the actual pictures in the slideshow, changing every two seconds.
Using Drag-and-Drop to Reorder Slides
The scaffolding we have for editing a slideshow shows just the slideshow attributes that are stored directly in the slideshows table: the slideshows name and the date on which it was created. The most important part is missing: the photos that are part of the slideshow!
By now, you’ve probably realized that this is because the scaffolding code deals with only one database table: the slideshows table. The relationship data about which photos are assigned to a slideshow and their order in the slideshow are stored in the slides table. Scaffolding does not handle relationships, so you have to write the code to edit this relationship data.
We’re going to display a list of thumbnails of all the photos that are in a slideshow, and then let the user reorder them using drag-and-drop. If you’ve had to struggle through implementing drag-and-drop before, you’re not going to believe how easy this is going to be. Here’s a hint: this will take a total 34 additional lines of Ruby, CSS, and RHTML template!
Let’s start by reviewing the current implementation of the edit action in the slideshow controller:
def edit
@slideshow = Slideshow.find(params[:id])
end
This action expects to find the ID of the slideshow to edit passed in as the id parameter, which is normally decoded from the URL. You find the slideshow with that ID and assign that slideshow object to the instance variable @slideshow, so that it can be accessed in the view template.
That is really all that’s needed here, so you won’t have to add any code to this method. The changes will start with the edit view template, so edit the template photos/app/views/slideshows/edit.rhtml and make it look like this (the changes are in bold):
<h1>Editing slideshow</h1>
<%= link_to ‘Play this Slideshow’,
:action => ’show’, :id => @slideshow %>
<div id=’slideshow-contents’>
<%= render :partial => ’show_slides_draggable’ %>
</div>
<div id=’slideshow-attributes’>
<%= start_form_tag :action => ‘update’, :id => @slideshow %>
<%= render :partial => ‘form’ %>
<%= submit_tag ‘Save Attributes’ %>
<%= end_form_tag %>
</div>
Notice that the existing <%= render :partial => ‘form’ %> is wrapped in a <div> tag with an id attribute of slideshow-attributes. You will use this name in one of your CSS files to control how this section is displayed.
There is also a completely new section that displays thumbnails of the photos in the slideshow:
<div id=’slideshow-contents’>
<%= render :partial => ’show_slides_draggable’ %>
</div>
This code also uses a <div> tag with an id attribute, for the same reason: to use a CSS file to control its appearance. This div also renders a new partial view template named show_slides_draggable, which we will create next.
Create the file photos/app/views/slideshows/_show_slides_draggable.rhtml with the following contents:
<ol id=’sortable_thumbs’>
<% for slide in @slideshow.slides %>
<li id=’thumbs_<%= slide.id %>’ class=’slides’>
<%= thumbnail_tag slide %>
</li>
<% end %>
</ol>
<%= sortable_element(’sortable_thumbs’,
:url => {:action => ‘update_slide_order’}) %>
The first part is pretty standard stuff. We’re creating an HTML ordered list, in which each list item is a thumbnail image of one of the photos in the slideshow (note that the thumbnail_tag helper function that was created earlier). However, it’s the last two lines that do the heavy lifting.
sortable_element is a helper function that generates the JavaScript code that turns our list into a user-sortable, drag-and-drop-capable list. It wraps this list an HTML form, and the :url option specifies the URL to post to the server whenever the user changes the order of the list. In this case, it calls the action method update_slide_order in our slideshow controller. This call works in the background using an Ajax call.
The update_slide_order method is pretty simple as well. Edit photos/app/controllers/ slideshows_controller.rb, and add this method:
def update_slide_order
params[:sortable_thumbs].each_with_index do |id, position|
Slide.update(id, :position => position)
end
end
This method iterates through each slide in the list, extracting its ID and position in the list, and uses this information to update that slide’s database row with its new position. Let’s walk through this code in a little more detail:
We’re almost ready to give it a try, but first let’s edit photos/public/stylesheets/slideshows.css and add some formatting instructions for the two div IDs we created. Add the following at the end of the file:
#slideshow-contents {
float: left;
width: 11em;
padding: 0.50em;
text-align: center;
border-right: thin solid #bbb;
padding: 0.50em;
padding-bottom: 10em;
}
#slideshow-attributes {
margin-left: 23em;
padding-left: 1.5em;
padding-top: 1.5em;
}
This causes the contents of the slideshow (which will be a list of thumbnail images) to be displayed down the left side of the page, and the slideshow’s attributes will be displayed immediately to the right of the thumbnails.
Let’s see how this looks. Browse to http://127.0.0.1:3000/slideshows/list, and click the edit link for our one and only slideshow. It will look like Figure 6-2.
Click on one of the photos, and try dragging it around. When you drop it into a new location, update_slide_order is called to write the new order to the database.
Lets fix one minor thing here before we move on. Wouldn’t it be better to see the number of each photo appear vertically aligned in the middle of the thumbnail instead of at the bottom? Because the HTML for each thumbnail image is created by…
Figure 6-2. A drag-and-drop list of photos
…
our own helper function, thumbnail_tag, we just need to edit that function and add a vertical-align style attribute.
First, edit photos/app/helpers/slideshows_helper.rb, and add the code shown in bold:
module SlideshowsHelper
def thumbnail_tag(slide)
image_tag(”photos/#{slide.photo.thumbnail}”,
:style=>”vertical-align:middle”) if slide
end
end
Now, refresh your browser: the list numbers are nicely centered, as you can see in Figure 6-3.
With a very small amount of code, we added a very nice drag-and-drop user interface for reordering the slides in a slideshow. But we’re just getting started with our Ajax-enabled user interface.
Figure 6-3. Nicely centered list numbers
Please check back tomorrow for the conclusion to this article.
—
by O’Reilly Media
Java and Flash offer real alternatives for those trying to build web applications that function more like desktop applications. However, they have their shortcomings. AJAX overcomes these shortcomings — especially if you use Ruby on Rails.
Interactivity and responsiveness has been considered the USP of desktop applications and not of web applications. Even though there exist mechanisms such as Java Applets and Flash files that provide interactivity and responsiveness up to a point, they are intrusive. That is, the user needs to install either a Java or a Flash plug-in.
However, with AJAX coming into the foreground, a non-intrusive way of providing interactive and responsive web applications has evolved. Even with AJAX, the problem is not fully solved for developers. The reason for this is the peripheral integration of AJAX in almost all the existing frameworks. Still, there are exceptions in the form of frameworks that provide AJAX-based functionalities as their core services. Ruby-on-Rails (RoR) is one of them.
In this discussion, I will be focusing on using AJAX with RoR. The first section will be a brief overview of AJAX. In the second section, I will detail the steps involved in AJAXifying the RoR application. In the last section, I will be developing a real world application using AJAX and RoR. That’s the agenda for this discussion.
AJAX: an Overview
By definition AJAX is “a technique that extends the traditional web application model to allow for in-page server requests.” In other words, AJAX provides the functionality to make on the fly requests to the server and present the response data to the user by modifying a part of the page without refreshing the whole page. AJAX is not a single technology; rather, it’s a combination of technologies. These technologies form the basic components of AJAX, which are:
The second component is an object of JavaScript itself. However the first ‘A’ of AJAX comes from it. The reason for this is detailed below.
JavaScript is the “J” in AJAX. It is the JavaScript that parses the response from the server and makes appropriate changes to the current page. Using JavaScript, one can change a paragraph, replace a product image or change the complete look and feel of the page without the intervention of the server. This reduces the bandwidth and makes the web site look more responsive to the user.
XMLHttpRequest is an object of JavaScript that not only allows the user to create or construct HTTP calls from within the script but also process the response sent by the server. It is available as an ActiveX control in Internet Explorer and as a JavaScript object in other browsers. Though it is known as XMLHttpRequest, one can wrap any kind of HTTP communication using it.
The first ‘A’ in AJAX, which stands for “Asynchronous,” comes at the “behest” of XMLHttpRequest. One of the abilities of XMLHttpRequest is to make a call to the web server in the background while the user continues to do his/her work on the UI. Whenever the response is received, the XMLHttpRequest accepts it and passes it over to the function that is registered to handle the response. Thus the request-response cycle is relieved off the paradigm of synchronous communication.
If one looks up the definition of XML on the net, the most common definition found is this: “XML (Extensible Markup Language) is a W3C initiative that allows information and services to be encoded with meaningful structure and semantics that computers and humans can understand and is great for information exchange, and can easily be extended to include user-specified and industry-specified tags.” The extensibility and the ability to provide data in a structured format is the main reason for XML to be the preferred response data format sent by the server. This doesn’t mean that the server can’t send data in any other format. It can send data in any format and XMLHttpRequest can accept and process it. However, since XML is a standard that is both extensible and structured, it is preferred over every other.
The next obvious question is how these three components fit in the overall picture. Here is an example of AJAX at work. It checks the validity of the username.
var xmlHttp;
function createXmlHttpRequest()
{
//check the type of browser and initialize XMLHttpRequest object
if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);
}
else if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
//alert(”inside elseif…”+xmlHttp);
}
}
//This method creates an instance of XMLHttpRequest and calls the server
//Then delegates the data processing to another function on receipt of data
function startRequest()
{
createXmlHttpRequest();
var u1=document.f1.user.value;
xmlHttp.open(”GET”,”validate.php?user=”+u1,true)
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.send(null);
}
//Does the handling of data and presentation of data
function handleStateChange()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
document.getElementById(”results”).innerHTML= xmlHttp.responseText;
}
else
{
alert(”Error loading pagen”+ xmlHttp.status +”:”+ xmlHttp.statusText);
}
}
}
function resetDisplay()
{
document.getElementById(”results”).innerHTML=” ”
}
The logic here is very simple, yet the amount of boilerplate code required is pretty high and the complexity of JavaScript increases with the increase in complexity of the logic of data processing and presentation. And I have not shown the logic at server-side. This is the story with almost all of the technology except Ruby-on-Rails. How RoR is different from the others is the topic of the next section.
Implementing AJAX
In the last section, the example demonstrated the complexity involved in AJAXifying an application having even the simplest logic to be implemented. So how can RoR make it simple? RoR does it by providing AJAX as one of its core functionalities. RoR has the prototype, effects, dragdrop and controls JavaScript libraries as built-in libraries. Secondly, a helper called JavaScriptHelper provides wrapping around JavaScript code so that switching between Ruby and JavaScript won’t be necessary. So RoR makes things simpler by wrapping JavaScript libraries and providing them as built-in RoR libraries.
Now let’s look at ways to use AJAX within RoR. To implement AJAX, RoR provides two basic ways which are:
The former is used with non-form HTML whereas the later is used with form and form based HTML elements.
The link_to_remote() is one of the simplest yet versatile and flexible helpers in RoR. It takes following parameters:
So what are the steps required to use link_to_remote()? The steps are as follows:
The steps are common to that of any typical RoR. That is the beauty of RoR. Of these steps, the third step is optional if rendering is taken care of by the action itself.
<%= javascript_include_tag “prototype” %>
Here is an example of a page having link_to_remote():
<html>
<head>
<title>Ajax Demo</title>
<%= javascript_include_tag “prototype” %>
</head>
<body>
<h1>What time is it?</h1>
<div id=”time_div”>
I don’t have the time, but
<%= link_to_remote( “click here”,
:update => “time_div”,
:url =>{ :action => :say_when }) %>
and I will look it up.
</div>
</body>
</html>
The link_to_remote() is passed three arguments: the text to be shown i.e. “click here”, the id of the link created which is “time_div” and the action to be called which is say_when. The next step is to implement the controller containing the action.
class DemoController < ApplicationController
def index
end
def say_when
render(:layout => false)
end
end
The render function is called with the layout option as false because only a part of the HTML page is being updated; hence there is no requirement of any Rails layout wrappers. The example of the second type is as follows:
class DemoController < ApplicationController
def index
end
def say_when
render_text “<p>The time is <b>” + DateTime.now.to_s + “</b></p>”
end
end
It uses render_text method to generate the response.
<p>The time is <b> <%=DateTime.now.to_s%>
</b></p>
That’s how link_to_remote() is used. Next let’s see how form_remote_tag() is used.
While dealing with links, link_to_remote() is handy but what about form elements? That’s where form_remote_tag() comes in. One can easily enable any Rails form to use AJAX using form_remote_tag(). It serializes and sends all the form elements to the server via XMLHttpRequest. All this is done automatically without any requirement for extra logic implementation. The form_remote_tag() takes three parameters:
To use the form_remote_tag() there are three steps:
The steps are similar to those of using link_to_remote(). Only the way they are implemented is different.
<html>
<head>
<title>Ajax List Demo</title>
<%= javascript_include_tag “prototype” %>
</head>
<body>
<h3>Add to list using Ajax</h3>
<%= form_remote_tag(:update => “my_list”,
:url => { :action => :add_item },
:position => “top” ) %>
New item text:
<%= text_field_tag :newitem %>
<%= submit_tag “Add item with Ajax” %>
<%= end_form_tag %>
<ul id=”my_list”>
<li>Original item… please add more!</li>
</ul>
</body>
</html>
Here the id of the element is given as my_list which is the id of the list that will be populated by the response provided by the action. The url specifies the action to be called and the position tells Rails to place the returned HTML snippet on the top of the element whose id has been specified in the update parameter. Now let’s look at the action.
class ListdemoController < ApplicationController
def index
end
def add_item
render_text “<li>” + params[:newitem] + “</li>”
end
end
whereas if the rendering is to be done by a template then the code would be:
class ListdemoController < ApplicationController
def index
end
def add_item
@item= params[:newitem]
render(:layout => false)
end
end
The only difference is that the parameter passed by form_remote_tag() is placed in a variable called item which can be used in the template.
<li> <%=@item%> </li>
That’s it.
So now you have seen how easy the steps are for creating an AJAX based application in RoR. Next I will develop a real world application using RoR and AJAX.
Ruby-on-Rails and AJAX
In real world applications one of the most required functionalities is to populate a combo box based on the data entered in a preceding field such as a text box or another combo box. In this example, I will be developing such a part for an application. This can be used with any application with slight modifications. It contains two components:
index.rhtml - the view which contains the combo box to be filled and the
combo box on the basis of which the filling has to be donePopulateController - the controller containing the action required for the
populating of the combo box.
Here is the index.rhtml:
<html>
<head>
<meta http-equiv=”content-type” content=”text/html; charset=utf-8″ />
<%= javascript_include_tag “prototype” %>
<title>Ajax Rails & Select lists</title>
</head>
<body>
<%= form_remote_tag(:update => “sel_con”,:url => {
:action => :create_select },
:position => “top”,:success => “$(’sel_con’).innerHTML=”” ) %>
<p>
Please select a sports category:
</p>
<p>
<%= select_tag “categories”,
“<option>Team</option><option>Individual</option>” %>
</p>
<div id=”sel_con”></div>
<p>
<%= submit_tag “Show Sports” %>
</p>
<%= end_form_tag %>
</body>
</html>
The combo box contains two values, team and individual. Based on the selection the second combo has to be populated and shown at the div having the id sel_con. If team is selected by the user, the second combo box would be filled with team events whereas in the case of individual, individual event is populated. The form_remote_tag is passed four parameters: the id of element to be updated, the action to be called, the position in which to place the result and what has to be done if the request is successfully executed. In this case the inner HTML is set to no value i.e. “”. Next is the controller:
class PopulateController < ApplicationController
def index
end
def create_select
indArr=[”Nordic Skiing”, “Inline Skating”,”Tennis”,
“Triathlon”,”Road Racing”,”Figure Skating”,
“Weight Lifting”,”Speed Skating”,”Snowboarding”];
teamArr=[”Soccer”,”Basketball”,”Football”,”Hockey”,
“Baseball”,”Lacrosse”];
str=”";
if params[:categories].index(’Team’) != nil
render :partial => “options”,
:locals => { :sports => teamArr,:sptype => “team”}
elsif params[:categories].index(’Individual’) != nil
render :partial => “options”,
:locals => { :sports => indArr, :sptype => “individual” }
else
str=”<select id=’individual’ name=’individual’>
<option>unknown</option></select>”;
render :text => str;
end
#end method
end
#end class definition
end
The create_select is the action where the logic for creating and populating the second combo box goes. First it creates two arrays with team and individual sports events. Then based on the parameter received, the combo box is created and populated. This is done in the statement
render :partial => “options”,
:locals => { :sports => teamArr,:sptype => “team”}
Now let’s look at _options.rhtml which is a partial template i.e. the a piece of HTML code that can be used again and again. Here is the code:
<select id=”<%= sptype %>” name=”<%= sptype %>”>
<% sports.each do |sport| %>
<option><%= sport %></option>
<% end %>
</select>
It first gives the combo box an id, iterates through the array passed and populates the combo box. That’s it. This completes the application. Though I had mentioned four libraries, I have introduced only one of them. In the next discussion, I will be focusing on UI using the other three libraries. Till then..
—
by A.P.Rajshekhar
19 Oct
Posted by ProCOM
on October 19, 2007 – 1:04 pm - 805 views
In this conclusion to a six-part series covering web development and Ruby on Rails, you’ll learn how to send error messages to your email and more. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O’Reilly, 2006; ISBN: 0596523696). Copyright © 2006 O’Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O’Reilly Media.
15.20 Automatically Sending Error Messages to Your Email
Problem
You want to receive a descriptive email message every time one of your users encounters an application error.
Solution
Any errors that occur while running your application are sent to the ActionController::Base#log_error method. If you’ve set up a mailer (as shown in Recipe 15.19) you can override this method and have it send mail to you. Your code should look something like this:
class ApplicationController < ActionController::Base
private
def log_error(exception)
super
Notification.deliver_error_message(exception,
clean_backtrace(exception),
session.instance_variable_get(”@data”),
params,
request.env
)
end
end
That code rounds up a wide variety of information about the state of the Rails request at the time of the failure. It captures the exception object, the corresponding backtrace, the session data, the CGI request parameters, and the values of all environment variables.
The overridden log_error calls Notification.deliver_error_messsage, which assumes you’ve created a mailer called “Notification”, and defined the method Notification.error_message. Here’s the implementation:
class Notification < ActionMailer::Base
def error_message(exception, trace, session, params, env, sent_on = Time.now)
@recipients = ‘me@mydomain.com’
@from = ‘error@mydomain.com’
@subject = “Error message:
#{env[’REQUEST_URI’]}”
@sent_on = sent_on
@body = {
:exception => exception,
:trace => trace,
:session => session,
:params => params,
:env => env
}
end
end
The template for this email looks like this:
<!– app/views/notification/error_message.rhtml –>
Time: <%= Time.now %>
Message: <%= @exception.message %>
Location: <%= @env[’REQUEST_URI’] %>
Action: <%= @params.delete(’action’) %> </td> </tr>
Controller: <%= @params.delete(’controller’) %> </td> </tr>
Query: <%= @env[’QUERY_STRING’] %> </td> </tr>
Method: <%= @env[’REQUEST_METHOD’] %> </td> </tr>
SSL: <%= @env[’SERVER_PORT’].to_i == 443 ? “true” : “false” %>
Agent: <%= @env[’HTTP_USER_AGENT’] %>
Backtrace
<%= @trace.to_a.join(”</p>\n<p>”) %>
Params
<% @params.each do |key, val| -%>
* <%= key %>: <%= val.to_yaml %>
<% end -%>
Session
<% @session.each do |key, val| -%>
* <%= key %>: <%= val.to_yaml %>
<% end -%>
Environment
<% @env.each do |key, val| -%>
* <%= key %>: <%= val %>
<% end -%>
Discussion
ActionController::Base#log_error gives you the flexibility to handle errors however you like. This is especially useful if your Rails application is hosted on a machine to which you have limited access: you can have errors sent to you, instead of written to a file you might not be able to see. Or you might prefer to record the errors in a database, so that you can look for patterns.
The method ApplicationController#log_error is declared private to avoid confusion. If it weren’t private, all of the controllers would think they had a log_error action defined. Users would be able to visit /<controller>/log_error and get Rails to act strangely.
See Also
15.21 Documenting Your Web Site
Problem
You want to document the controllers, models, and helpers of your web application so that the developers responsible for maintaining the application can understand how it works.
Solution
As with any other Ruby program, you document a Rails application by adding specially-formatted commands to your code. Here’s how to add documentation to the FooController class and one of its methods:
# The FooController controller contains miscellaneous functionality
# rejected from other controllers.
class FooController < ApplicationController
# The set_random action sets the @random_number instance variable
# to a random number.
def set_random
@random_number = rand*rand
end
end
The documentation for classes and methods goes before their declaration, not after.
When you’ve finished adding documentation comments to your application, go to your Rails application’s root directory and issue the rake appdoc command:
$ rake appdoc
This Rake task runs RDoc for your Rails application and generates a directory called doc/app. This directory contains a web site with the aggregate of all your documentation comments, cross-referenced against the source code. Open the doc/app/index.rhtml file in any web browser, and you can browse the generated documentation.
Discussion
Your RDoc comments can contain markup and special directives: you can describe your arguments in definition lists, and hide a class or method from documentation with the :nodoc: directive. This is covered in Recipe 17.11.
The only difference between Rails applications and other Ruby programs is that Rails comes with a Rakefile that defines an appdoc task. You don’t have to find or write one yourself.
You probably already put inline comments inside your methods, describing the action as it happens. Since the RDoc documentation contains a formatted version of the original source code, these comments will be visible to people going through the RDoc. These comments are formatted as Ruby source code, though, not as RDoc markup.
See Also
15.22 Unit Testing Your Web Site
Problem
You want to create a suite of automated tests that test the functionality of your Rails application.
Solution
Rails can’t write your test code any more than it can write your views and controllers for you, but it does make it easy to organize and run your automated tests.
Rails can’t write your test code any more than it can write your views and controllers for you, but it does make it easy to organize and run your automated tests.
When you use the ./script/generate command to create controllers and models, not only do you save time, but you also get a generated framework for unit and functional tests. You can get pretty good test coverage by filling in the framework with tests for the functionality you write.
So far, all the examples in this chapter have run against a Rails application’s development database, so you only needed to make sure that the development section of your config/database.yml file was set up correctly. Unit test code runs on your application’s test database, so now you need to set up your test section as well. Your mywebapp_test database doesn’t have to have any tables in it, but it must exist and be accessible to Rails.
When you generate a model with the generate script, Rails also generates a unit test script for the model in the test directory. It also creates a fixture, a YAML file containing test data to be loaded into the mywebapp_test database. This is the data against which your unit tests will run:
./script/generate model User
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/user.rb
create test/unit/user_test.rb
create test/fixtures/users.yml
create db/migrate
create db/migrate/ 001_create_users.rb
When you generate a controller with generate, Rails creates a functional test script for the controller:
./script/generate users list
exists app/controllers/
exists app/helpers/
create app/views/users
exists test/functional/
create app/controllers/ users_controller.rb
create test/functional/ users_controller_test.rb
create app/helpers/
users_helper.r b
create app/views/users/list.rhtml
As you write code in the model and controller classes, you’ll write corresponding tests in these files.
To run the unit and functional tests, invoke the rake command in your home directory. The default Rake task runs all of your tests. If you run it immediately after generating your test files, it’ll look something like this:
$ rake
(in /home/lucas/mywebapp)
/usr/bin/ruby1.8 “test/unit/user_test.rb”
Started
.
Finished in 0.048702 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
/usr/bin/ruby1.8 “test/functional/users_controller_test.rb”
Started
.
Finished in 0.024615 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
Discussion
All the lessons for writing unit tests in other languages and in other Ruby programs (see Recipe 17.7) apply to Rails. Rails does some accounting for you, and it defines some useful new assertions (see below), but you still have to do the work. The rewards are the same, too: you can modify and refactor your code with confidence, knowing that if something breaks, your tests will break. You’ll hear about the problem immediately and you’ll be able to fix it more quickly.
Let’s see what Rails has generated for us. Here’s a generated test/unit/user_test.rb:
require File.dirname(__FILE__) + ‘/../test_helper’
class UserTest < Test::Unit::TestCase
fixtures :users
# Replace this with your real tests.
def test_truth
assert true
end
end
A good start, but test_truth is kind of tautological. Here’s a slightly more realistic test:
class UserTest
def test_first
assert_kind_of User, users(:first)
end
end
This code fetches the first element from the users table, and asserts that ActiveRecord turns it into a User object. This isn’t testing our User code (we haven’t written any) so much as it’s testing Rails and ActiveRecord, but it shows you the kind of assertion that makes for good unit tests.
But how does users(:first) return anything? The test suite runs against the mywebapp_test database, and we didn’t even put any tables in it, much less sample data.
We didn’t, but Rails did. When you run the test suite, Rails copies the schema of the development database to the test database. Instead of running every test against whatever data happens to exist in the development database, Rails loads special test data from YAML files called fixtures. The fixture files contain whatever database data you need to test: objects that only exist to be deleted by a test, strange relation ships between rows in different tables, or anything else you need.
In the example above, the fixture for the users table was loaded by the line fixtures :users. Here’s the generated fixture for the User model, in test/fixtures/users.yml:
first:
id: 1
another:
id: 2
Before running the unit tests, Rails reads this file, creates two rows in the users table, and defines aliases for them (:first and :another) so you can refer to them in your unit tests. It then defines the users method (like so much else, this method name is based on the name of the model). In test_first, the call to users(:first) retrieves the User object corresponding to :first in the fixture: the object with ID 1.
Here’s another unit test:
class UserTest
def test_another
assert_kind_of User, users(:another)
assert_equal 2, users(:another).id
assert_not_equal users(:first), users(:another)
end
end
Rails adds the following Rails-specific assertions to Ruby’s Test::Unit:
See Also
15.23 Using breakpoint in Your Web Application
Problem
Your Rails application has a bug that you can’t find using log messages. You need a heavy-duty debugging tool that lets you inspect the full state of your application at any given point.
Solution
The breakpoint library lets you stop the flow of code and drop into irb, an interactive Ruby session. Within irb you can inspect the variables local to the current scope, modify those variables, and resume execution of the normal flow of code. If you have ever spent hours trying to track down a bug by placing logging messages everywhere, you’ll find that breakpoint gives you a much easier and more straightforward way to debug.
But how can you run an interactive console program from a web application? The answer is to have a console program running beforehand, listening for calls from the Rails server.
The first step is to run ./script/breakpointer on the command line. This command starts a server that listens over the network for breakpoint calls from the Rails server. Keep this program running in a terminal window: this is where the irb session will start up:
$ ./script/breakpointer
No connection to breakpoint service at druby://localhost:42531
Tries to connect will be made every 2 seconds…
To trigger an irb session, you can call the breakpoint method anywhere you like from your Rails application–within a model, controller, or helper method. When execution reaches that point, processing of the incoming client request will stop, and an irb session will start in your terminal. When you quit the session, processing of the request will resume.
Discussion
Here’s an example. Let’s say you’ve written the following controller, and you’re having trouble modifying the name attribute of an Item object.
class ItemsController < ApplicationController
def update
@item = Item.find(params[:id])
@item.value = ‘[default]’
@item.name = params[:name]
@item.save
render :text => ‘Saved’
end
end
You can put a breakpoint call in the Item class, like this:
class Item < ActiveRecord::Base
attr_accessor :name, :value
def name=(name)
super
breakpoint
end
end
Accessing the URL http://localhost:3000/items/update/123?name=Foo calls Item-Controller#update, which finds Item number 123 and then calls its name= method. The call to name= triggers the breakpoint. Instead of rendering the text “Saved”, the site seems to hang and become unresponsive to requests.
But if you return to the terminal running the breakpointer server, you’ll see that an interactive Ruby session has started. This session allows you to play with all the local variables and methods at the point where the breakpoint was called:
Executing break point “Item#name=” at item.rb:4 in `name=’
irb:001:0> local_variables
=> [”name”, “value”, “_”, “__”]
irb:002:0> [name, value]
=> [”Foo”, “[default]”]
irb:003:0> [@name, @value]
=> [”Foo”, “[default]”]
irb:004:0> self
=> #<Item:0×292fbe8 @name=”Foo”, @value=”[default]”>
irb:005:0> self.value = “Bar”
=> “Bar”
irb:006:0> save
=> true
irb:006:0> exit
Server exited. Closing connection…
Once you finish, type exit to terminate the interactive Ruby session. The Rails application continues running at the place it left off, rendering “Saved” as expected.
By default, breakpoints are named for the method in which they appear. You can pass a string into breakpoint to get a more descriptive name. This is especially helpful if one method contains several breakpoints:
breakpoint “Trying to set Item#name, just called super”
Instead of calling breakpoint directly, you can also call assert, a method which takes a code block. If the block evaluates to false, Ruby calls breakpoint; otherwise, things continue as normal. Using assert lets you set breakpoints that are only called when something goes wrong (called “conditional breakpoints” in traditional debuggers):
1.upto 10 do |i|
assert { Person.find(i) }
p = Person.find(i)
p.update_attribute(:name, ‘Lucas’)
end
If all of the required Person objects are found, the breakpoint is never called, because Person.find always returns true. If one of the Person objects is missing, Ruby calls the breakpoint method and you get an irb session to investigate.
Breakpoint is a powerful tool that can vastly simplify your debugging process. It can be hard to understand the true power of it until you try it yourself, so go through the solution with your own code to toy around with it.
See Also
————————————————-
* Python, for instance, has several excellent web application frameworks, but that’s just the problem. It has several, and a powerful community is fractured on the issue of which to use. Ruby has no major web application frameworks apart from Rails. In a sense, Ruby’s former obscurity is what made the dominance of Rails possible.
* You could throw an exception, but then your redirect wouldn’t happen: the user would see an exception screen instead.
* More precisely, our models have been embedded in our controllers, as ad hoc data structures like hardcoded shopping lists.
* The helper function time_ago_in_words() calculates how long it’s been since a certain time and returns English text such as “about a minute” or “5 hours” or “2 days”. This is a nice, easy way to give the user a perspective on what a date means.
* Rails extends Ruby’s numeric classes to include some very helpful methods (like the hour method shown here). These methods convert the given unit to seconds. For example, Time.now + 1.hour is the same as Time. now + 3600, since 1.hour returns the number of seconds in an hour. Other helpful methods include minutes, hours, days, months, weeks, and years. Since they all convert to numbers of seconds, you can even add them together like 1.week + 3.days.
* This doesn’t quite stand for Asynchronous JavaScript and XML. The origins of the term Ajax are now a part of computing mythology, but it is not an acronym.
* This will happen if someone’s using your application with JavaScript turned off.
* You can even add your web interface actions to the ItemController class. Then a single controller will implement both the traditional web interface and the web service interface. But you can’t define a web application action with the same name as a web service action, because a controller class can contain only one method with a given name.
—-
by O’Reilly Media