Using Cooliris with Ruby on Rails

Posted on 28 January 2009

Cooliris (formally known as PicLens) is a great way of viewing images on the web, and it's really easy to make your Ruby on Rails app compatible. You just need to create an xml version of your page and Cooliris will read it like an rss feed.

First create your Cooliris xml template in /views/layouts/cooliris.rxml

xml.instruct!

xml.rss "version" => "2.0", "xmlns:media" => "http://search.yahoo.com/mrss" do
 xml.channel do

   xml.title       @title
   xml.description @description
   xml.icon        "/images/your_logo.png"

   @images.each do |image|
     xml.item do
       xml.title            image.reference_number
       xml.link             images_url(:action => :view, :id => image)
       xml.guid             images_url(:action => :view, :id => image)
       xml.media:content, :url => image.authenticated_s3_url('public'), :type => "image/jpeg"
       xml.media:thumbnail, :url => image.authenticated_s3_url('public'), :type => "image/jpeg"
     end
   end

 end
end

Obviously tweak the details where necessary, xml.link needs to point to the html page and the xml.media:content needs to be the path to the image itself.

Then in your controller action you need to make sure you tell rails what to do when the xml version of the page is requested...

images = Image.all

respond_to do |format|
  format.html do
    @cooliris = true
    @images = images.paginate :page => params[:page]
  end
  format.xml do
    @title = "My Images"
    @description = "Description of my images"
    @images = images
    render :template => "/layouts/cooliris", :layout => false
  end
end

Note that the xml version loads all images whereas the html version paginates. This means Cooliris wont be limited to just showing the images on that corresponding html page.

In the head of your layout template you need to add an auto discovery link that points to your xml page.

<% if @cooliris %>
	<link rel="alternate" href="<%= request.request_uri + ".xml" %>" type="application/rss xml" />
<% end %>

I used an instance variable that is set in the controller action to ensure the link is only displayed when the Cooliris xml page is available.

You are probably all done now, unless you aren't using restful routes. Basically you need to ensure you have a route that accepts the :format param so that Rails can serve the xml version of the page. Eg.

map.connect '/images/:action/:id.:format', :controller => "images"

That's it!

Comments left...

  • I am trying to embed the cooliris wall in my website and I am just a begginer and I am totally lost. I need something in actual code that i could copy. Is that possible anybody?

    Jonathan at 21 May 09 at 10:59

Got something to say?