Such joy from such little code! 5

Posted by brian Thursday, January 05, 2006 22:21:00 GMT

For those of you who don’t already know about flickr.rb, you’ve got to check it out. It’s an insanely simple library that’s going to help you get that Flickr/Google Maps/Yahoo!/Craigslist/Hostess Twinkie mash-up you’ve always dreamed about off the ground.

As a quick example, let’s just say you wanted to create a minimal Flickr photostream, just for fun. You want to grab all the public Flickr photos tagged “dog”, and show them randomly on a page via AJAX, and maybe do a little script.aculo.us fade in and out.

First, gem install flickr. Great, now that’s over with.

The controller:

require 'flickr'

class PhotoController < ApplicationController
    def show
        get_image
    end

    def photo
        get_image
        render :partial => 'photo'
    end

    def get_image
        flickr = Flickr.new
        @photos = flickr.tag('dog')
        @img = @photos[rand(@photos.length)]
    end
end

The view:

<div id="the_image">
    <%= render :partial => 'photo' %>
    <%= periodically_call_remote(
        :update => "the_image", 
        :url => {:action => "photo"},
        :loading => "new Effect.Fade('the_image')",
        :complete => "new Effect.Appear('the_image')") %>
</div>

The partial:

<h3><%= @img.title %></h3>
<p><%= @img.description %></p>
<p><%= image_tag(@img.source) %></p>

Clearly, we could optimize this by throwing all the photo data into a database, so that we don’t have to make the API call with every request. And of course, you can do other, more complex things with flickr.rb, like grabbing photos by user/tag/recently added/related tags, etc.

There’s a Flickr API wrapper for .NET, too. Anybody want to re-create this example with ASP.NET so we can compare?

Comments

Leave a response

  1. Eifion   January 07, 2006 @ 02:55 PM

    Interesting article, though made slightly baffling by the fact that Safari hides the embedded Ruby in the view and the partial on this page. (it's fine in FireFox). Impressive though Ruby and Rails are even I was wondering how it was going to render stuff into an empy DIV and three empty Ps.

  2. Brian   January 07, 2006 @ 06:39 PM

    Eifion: sorry about that, I seem to have forgotten to escape a couple of characters in the post. Sadly, I have no way to test it on Safari :( So lemme know if it looks better now.

  3. Eifion   January 07, 2006 @ 07:34 PM

    Yes, it's fine now. By the way a friend of mine had a play with the .Net API for Flickr. I don't know how much code he had to write but he was up until 1am trying to get it to work.

  4. Robert Brook   January 10, 2006 @ 12:30 PM

    Wonderful!

  5. Bryan   February 02, 2007 @ 04:53 AM

    Hey, good work! But it looks a little funky on Firefox - your blog software is auto-formatting the ampersands as (& a m p;) so the view and the partial show the unescaped HTML characters...

Comment


(won't be published)