Connect Your Rails App to Flickr With The Fleakr Gem

Fleakr started out as a simple way for me to download photos through the console (something it does quite well), but it is also really easy to use inside your Rails application.

Let's build a sample app that displays the latest photos for a specific Flickr user. First, install the gem and create your Rails app:

$ sudo gem install fleakr
$ rails fleakr-demo

Configure the gem inside your application:

# config/environment.rb
config.gem 'fleakr'

Since we're doing read-only calls, we only need an API key - let's set that in an initializer:

# config/initializers/fleakr.rb
Fleakr.api_key = 'your_api_key_here'

Now we'll create a simple action that will accept a Flickr user as a parameter and pull back the recent photos:

$ script/generate controller users show

Then, add a route (and remember to delete public/index.html):

# config/routes.rb
map.user ':username', :controller => 'users', :action => 'show'

Add a line to retrieve the specified user:

class UsersController < ApplicationController

  def show
    @user = Fleakr.user(params[:username])
  end

end

Finally, create some simple view code to pull back the latest photos (limited to 100) in groups of 10

<% # app/views/users/show.html.erb %>
<% @user.photos.each_slice(10) do |photos| %>
  <div>
  <% photos.each do |photo| %>
    <%= link_to image_tag(photo.square.url), 
          photo.url, 
          :width => photo.square.width, 
          :height => photo.square.height %>
  <% end %>
  </div>
<% end %>

You're all set - start up your server and point your browser to a URL containing a Flickr username (e.g. http://localhost:3000/teamviget).

Warning: This is extremely inefficent and is designed only to show you what's possible and shouldn't be used in a production application. The rendering of this view can take up to a minute because it has to do N + 1 API calls (where N is the number of recent photos, capped at 100).

blog comments powered by Disqus