Putting Flickr on Rails

Contributed by Brian Leonard
November 2007
[Revision number: V6.0-5]

This tutorial describes how to create a Ruby on Rails application that searches the Flickr database.

Note: This tutorial requires direct connection to the Internet and does not work if you are working behind a proxy.

Contents

Tutorial Requirements
Obtaining a Flickr API Key
Installing the Flickr Library
Creating the Ruby on Rails Project
Adding Style to the Project
Creating a Controller
Defining the Search Method
Running the Application
Improving the User Experience
Content on this page applies to NetBeans IDE 6.0

Tutorial Requirements

This tutorial requires the following technology:

Obtaining a Flickr API Key

You must have an API key to make use of the Flickr API.
  1. In your web browser, go to http://www.flickr.com/services/api/misc.api_keys.html.
  2. Click Apply for your key online now.
  3. Follow the steps for obtaining a Flickr key.
  4. Copy the API key that Flickr generates and save it in a text file or other convenient location.

Installing the Flickr Library

  1. From the Tools menu, choose Ruby Gems.
  2. In the Ruby Gems dialog box, click the New Gems tab.
  3. Type flickr in the Search field and press Enter.
  4. Select flickr, and then click Install. Click OK in the Gem Installation Settings dialog box.
  5. Make sure you get a success message, and then close the dialog boxes.

Creating the Ruby on Rails Project

  1. Choose File > New Project.
  2. Select Ruby in the Categories field and Ruby on Rails Application in the Projects field and click Next.
  3. Type Flickr in the Project Name field and click Finish.

    The Flickr library expects you to add your Flickr API Key directly to its script. You could do that, however, the approach described in the following steps enables you to use the Flickr library without touching it.
  4. In the Projects window, expand the Configuration node, then open environment.rb.
  5. Add the following code at the bottom of the environment.rb file. Be sure to enter your Flicker API Key in the MY_KEY variable. You need the key to access the Flickr APIs.

    Code Sample 1: Adding Your Flickr API Key
    require 'rubygems'
    require 'flickr'
    MY_KEY='Enter your Flicker API Key'
    class Flickr
      alias old_initialize initialize
      def initialize(api_key=MY_KEY, email=nil, password=nil)
        puts "new_initialize " + MY_KEY
        old_initialize(api_key, email, password)
        @host="http://api.flickr.com"
        @activity_file='flickr_activity_cache.xml'
      end
    end

  6. From the main menu, choose File > Save All.

Adding Style to the Project

  1. In the Project window, expand the Views node, right-click the layouts node, and choose New -> RHTML file. Name the file application and click Finish.
  2. Replace the existing code in application.rhtml with the following code:

    Code Sample 2: Code for application.rhtml
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
    <html>
        <head>
        <title>Flickr</title>
          <%= javascript_include_tag :defaults %>
          <%= stylesheet_link_tag 'flickr' %>
        </head>
    <body>
          <%= yield %>
    </body>
    </html>

  3. Expand the Public node, right-click stylesheets and choose New > Other.
  4. In the New File dialog box, set the Category to Other and the File Type to Cascading Style Sheet. Click Next.
  5. Name the file flickr and click Finish.

    The file flickr.css opens in the editing area.
  6. Add the following styles to flickr.css:

    Code Sample 3: Style Code
    body {
        background-color: #888;
        font-family: Lucida Grande;
        font-size: 11px;
        margin: 25px;
    }

    form { margin: 0; margin-bottom: 10px; background-color: rgb(222,231,236); border: 5px solid #333; padding: 25px; }
    fieldset { border: none; } #spinner {
    float: right;
    margin: 10px;
    }

    #photos img { border: 1px solid #000; width: 75px; height: 75px; margin: 5px; }

Creating a Controller

  1. Right-click the Controllers node and choose Generate.
  2. In the Rails Generator dialog box, type flickr in the Name field and index in the Views field, and then click OK.

    This action creates the file flickr_controller.rb and opens the file in the editing area.
  3. Expand Views > flickr and open index.rhtml.
  4. Replace the existing code in index.rhtml with the following code:

    Code Sample 4: Code for index.rhtml
    <% form_remote_tag :url => {:action => 'search'}, :update => 'photos' do %>
        <fieldset>
            <label for="tags">Tags:</label>
    
            <%= text_field_tag 'tags' %>
            <%= submit_tag 'Find' %>
        </fieldset>
    <div id="photos"></div> <% end %>

Defining the Search Method

  1. Open flickr_controller.rb.
  2. Edit the code by deleting the index method and replacing it with the search method shown in bold:

    Code Sample 5: Code FlickrController Class
    class FlickrController < ApplicationController
      def search
        flickr = Flickr.new
        render :partial => 'photo', :collection =>
          flickr.photos(:tags => params[:tags], :per_page => '24')
      end
      
    end

  3. Under the Views node, right-click the flickr node and choose New -> RHTML file. Name the file _photo and click Finish.

  4. Replace the contents of the file so that the file includes the following line only:

    <img class='photo' src="<%= photo.sizes[0]['source'] %>">
    

Running the Application

Here you configure the environment so that running the project launches the application.
  1. If the WEBrick server is running, stop the server by clicking the red X icon in the Output window, as shown in the following figure:

    Figure 1: Stopping the WEBrick Server

    Figure 1:  Stopping the WEBrick server

  2. Under the Public node, delete index.html.
  3. Under the Configuration node, open routes.rb. Find the line:

    # map.connect '', :controller => "welcome"
    	
  4. Edit the line by removing the comment sign (#) and changing welcome to flickr.
  5. Click the Run Main Project button in the toolbar to start the WEBrick server and launch the browser, as shown in the following figure.

    Figure 2: Flickr Application

    Figure 2: Flickr Application
  6. Enter a search string, such as NetBeans, and click Find. Give the images a couple of seconds to load.

    Figure 3: Loading Images

    Figure 3: Loading an Image

Improving the User Experience

When you click the Find button, there's no feedback that something's happening behind the scenes. Here you add a simple animated gif to help address this problem as well as change the effect of the images as they load.
  1. Save this animated gif from your browser to a file on your desktop. Then drag the file under the Public > images node in the Project window in the NetBeans IDE.
  2. Open Views > flickr > index.rhtml. Delete the existing code, and replace it with the code shown in the following sample:

    Code Sample 6: Code for index.rhtml
    <% form_remote_tag :url => {:action => 'search'}, :update => 'photos', 
        :complete => visual_effect(:blind_down, 'photos'),
        :before   => %(Element.show('spinner')),
        :success  => %(Element.hide('spinner')) do %>
    
        <%= image_tag 'spinner.gif', :id => 'spinner', :style => 'display: none' %>
        <fieldset>
            <label for="tags">Tags:</label>
            <%= text_field_tag 'tags' %>
    
            <%= submit_tag 'Find' %>
        </fieldset>
    	
        <div id="photos" style="display: none"></div>
    	
    <% end %>

  3. From the main menu, choose File > Save All. Refresh your browser and try another search string, such as JRuby.

    Figure 4: Adding Animation

    Figure 4:  Adding Animation

    Now you see a simple animation to let you know the server is working on your request. When the images appear, they drop down like a set of blinds.

Next Steps



Send Us Your Feedback