Delicious with Ruby on Rails - JSON

I recently (well about a month ago!) read a very good post that informs you how to add your delicious links to your rails app.

I was using that method and all was well, until I got a request that the links should open in a new window. With the simple html access to my links, that was not an option you can pass. So I had to resort to using something more complicated; JSON seemed the easiest for me to read in and manipulate.

I would advise you to follow this tutorial and then come back here and see how the code can be changed to use JSON instead of the HTML api.

You will need to install the JSON ruby library first.

gem install json

If that does not work just download it from here and run the install script.

Here is the modified method


def delicious_links(limit ="20", aclass="grey")
    begin
      unless read_fragment(:action => 'delicious_links')
        logger.info "Getting new delicious_links" 
        require "open-uri" 
        require 'json'
        @delicious_links = "" 
        link = "http://del.icio.us/feeds/json/YOUR_USERNAME_HERE?raw=true&count="+limit
        @jsonObject = "" 

        open(link) {|f|
          f.each_line {|line| @jsonObject += line }
        }
        @urls = parse(@jsonObject)

        for i in 0...@urls.length
          @url_obj = @urls.fetch(i)
          url ="" 
          title ="" 
          tags ="" 
          @url_obj.each {|key, value|  
           url = value if key == "u" 
           title = value if key == "d" 
           tags = value if key == "t" 
          }
          @delicious_links += "<div class=\"blogSideBarLink\">" + "<a href= \""+url+"\" target=\"blank_\" class=\""+aclass+"\">"+ title+"</a></div>"            
        end
      end
    rescue
      @delicious_links = "Not available @ this time" 
    end
    logger.info "delicious_links finished" 
    render_without_layout
  end