Ajax Spy in Rails

I was playing around with Digg this morning and noticed Digg Spy. At first I thought it was really cool and wondered how they did that. Then I realized it’s just a bit of Ajax and, as anyone who’s read Pragmatic Ajax knows, Ajax is easy! So read on for how I implemented an Ajax spy in Rails and to download the code. The first thing I did was generate a controller and model using Rich White’s excellentAjaxScaffold Generator, called EntriesController and Entry, respectively. This gave me a nice way to create new entries easily. After that I added some basic login/signup support so that the entries could be associated with users. So far, nothing out of the ordinary. Next I created a new controller called SpyController, this is where all of the action happens. I added a basic list method which just returns all of the entries in the DB (sorry, no pagination), this is what we initially call when displaying the page. Then I added an update method which will be called periodically to retrieve new entries, it looks like this:

~~~~ {lang=“ruby”} def update last_update = Time.parse(params[:timestamp]) # locate all of the entries created since the last update @entries = Entry.find(:all, :order => ‘created_at ASC’, :conditions => [ ‘created_at > ?’, last_update.to_s(:db) ]); if !@entries.empty?

render :update do |page|
  for entry in @entries
    page.insert_html(:top, 'spy-list', :partial => 'entry', :object => entry)
    page.visual_effect :highlight, "spy-item-#{entry.id}"
  end
end

end end ~~~~

At this point I needed some JavaScript to call the update method, so put the following code in application.js:

~~~~ {lang=“ruby”} var updateInterval = 5000; // update every 5 seconds var timestamp = new Date().toUTCString(); var timer;

function go() { timer = setInterval(‘update()’, updateInterval); }

function update() { url = “/spy/update”; new Ajax.Request(url, {

           asynchronous: true,
           method: "get",
           parameters: "timestamp=" + timestamp,
           onSuccess: function(request) {
             timestamp = new Date().toUTCString();
           }

}); } ~~~~

The JavaScript update method calls the SpyController’s update method and passes a timestamp as a parameter (this is the time when the page was loaded, initially, and later the timestamp is updated as new entries are retrieved). To bring it all together I had to add on onload to the list.rhtml view for the SpyController, like this:

~~~~ {lang=“html”} This page updates automatically!

<% if !@entries.empty? %>

<%= render :partial => 'entry', :collection => @entries, :locals => { :hidden => false } %>

<% end %> ~~~~

That’s all there is to it. See, I told you it’s easy! You can download the code from here (Updated for Rails 1.2.3).

I’m in Rails Recipes!

Chad Fowler has graciously accepted one of my recipes for inclusion in his new book, Rails Recipes! It’s recipe #65, “Easy HTML Whitelists�, in the latest beta version of the book. If you haven’t already pre-ordered your copy, I suggest you click over to the Pragmatic Programmers website and do so now. The other 69 recipes are just as good (if not better).

Putting Flickr on Rails

You know that really cool screencast at the Ruby on Rails website where Rails is used to create a Flickr interface in 5 minutes? Well, I followed the screencast and built my own copy and then I enhanced it with some additional JavaScript (Lightbox style preview of the images and a blind-up on subsequent searches). Note that in the course of making my changes I found out the proper ordering of the JavaScript callbacks (see this) – even though you would think that :before would be called prior to a :complete, it doesn’t always happen that way (so sometimes the new results are blinded-up and not shown).

I’ve been meaning to upload this for awhile, but just haven’t gotten around to it. So today I updated it to work with Rails 1.1.1 (though didn’t switch the Ajax-y goodness over to RJS). Hopefully other folks can benefit from the code. To run it all you have to do is first install the flickr ruby gem, like so:

sudo gem install flickr

and unzip and run this Rails app. Enjoy!

The Use of Superconducting Wire in Ethernet Networks

I’m curious why I can’t find anyone experimenting with the use of superconductors (high temperature superconducting (HTS) wire, specifically) in networking applications. I realize that fiber is really cheap now and HTS wiring is not. But it would be nice to see the transmission distances, for example, for an HTS version of Cat 6 with RJ-45 style connectors. I find it annoying that you have to clean/polish the ends of fiber and dealing with two connectors is a pain. Though I think the LC duplex connectors are an improvement over the SC/FC/ST connectors. Plus I’ve seen what happens when you bend fibers too far and have to replace or splice it. Then again, I’m not that familiar with HTS wire so it may have some of the same issues (though surely it can’t be as brittle as glass). Since fiber supports DWDM, I don’t think HTS cable will take off, but it would still be interesting to see the comparison. This would be core network/long haul usage … in the long run, I think that wireless will win out in the last mile since it doesn’t require the expense of burying fiber. If anyone knows more about HTS wire being used in networking applications please send me an email or leave a comment here. Thanks.

NoVARUG March Meeting

I’m a bit late in posting about it (due to extreme busyness at home and at work), but Devin Mullins gave a nice overview of metaprogramming with Ruby at the March Northern VA Ruby Users Group meeting. Devin’s talk, entitled “The Tao of Metaprogramming”, was more of an exploration of Ruby’s metaprogramming support in an irb session than the standard PowerPoint/Keynote presentation. He covered the reflection support in Ruby to see which methods a class responds to as well as how to add methods dynamically to object instances and classes using define_method, instance_method, class_eval, method_missing and eval. Ostensibly, the talk was subtitled “ActiveRecord’s Not Black Magic” but due to the number of questions/discussion we didn’t get into ActiveRecord that much — Devin did start to discuss it but I felt that we only scratched the surface. Overall, I though it was a very good talk and cleared up some of my questions regarding metaprogramming in Ruby. I still wish that someone (preferably the Pragmatic Programmers) would publish a book with a focus on metaprogramming in Ruby and writing domain specific languages. Why’s discussion of writing a DSL in Ruby called Dwemthy’s Array is nice (and funny), but I’d like to see something deeper. Perhaps, I’m wrong and it’s not enough for a full length book, but I’d be willing to pay for a Fridays type of short PDF if it were available.