You won’t need the API key any more so you can eat that piece of paper.

Step 5: Have a play!

Right. Time to mess with it! What we are going to do now is fire up the rails console and retrieve some of your images. However the flickr APIs need to know your Flickr ID. For this we will use a website called idGettr

What you do is paste in the URL for your Flickr photostream and it spits out your Flickr ID which we can then use with the APIs. So for me I typed in http://www.flickr.com/photos/antonjenkins/ and it returned an ID of 12864272@N02.

Write this down somewhere, memorise it and then eat the piece of paper.

So we’re very happy now – we’re using ruby to talk to Flickr! What we need to do now is get this on to our website.

Step 6: Writing a flickr helper

It’s a good idea to separate out functionality like this into helpers and partials, rather than weave it directly into your existing code. So we’re going to create a flickr_helper.rb in the app/helpers directory like so:

Each flickr thumbnail is placed on top of a little fake polaroid image I knocked up:

You may have also noticed a call in our flickr helper to an unavailable partial if there was an exception whilst trying to speak to flickr:

123

rescueException render :partial => '/flickr/unavailable'end

I’m leaving that partial blank so if flickr is down it just doesn’t render anything. But if you want you can display something else instead of the flickr output then place it in the _unavailable.html.erb partial.

Step 7: Call the helper in your application.html.erb layout template

Just a simple call to…

1

<%= render_flickr_sidebar_widget('12864272@N02') %>

Of course you’ll put your own flickr ID in there instead of mine. Unless you really like my photos?! ;o)

Are we done yet?

Ah. Not quite! You may have noticed something about this when you started testing it…... it’s slow as hell! Every single page render now has to wait for a round trip to flickr. Not cool!

Step 8: Fragment caching to the rescue!

This is a perfect candidate for fragment caching. The flickr photos aren’t going to be changing too often so we can cache them and expire them when we know they have changed.

So we’re going to surround the call to the flickr helper in a fragment cache block:

Remember this won’t speed up your renders on your development server as caching is disabled by default in development, but on production it will fly. It won’t cache the images (and why would you want to as flickr is built to serve images?) but it will cache the actual HTML code which required the costly API calls to flickr in order to generate.

Now we need some code to expire this cache when you’ve added some photos to flickr and you want to update the photos on the website. In fact, it would be really cool if you could expire this cache using capistrano, so you wouldn’t even need to ssh into your server to do this. For this I refer you to my previous post on expiring page and fragment caches using capistrano.