Ruby class to fetch suggested keywords

August 4th, 2008 | by Sajal Kayan |

I have recently ditched Perl and fell for Ruby.

Here is a Ruby class which gets suggested keywords from yahoo API and presents it in a comma separated list. This might be useful for people who use Ruby to upload/edit multiple posts and need to tag them automagically.

This might be awfully simple for the hardcore guys, but for a noob like me, had I come across this example earlier it would have saved me an hour or so. Here it goes…

The Class :-

  1. # A ruby class to fetch suggested keywords using Yahoo’s term Extraction API
  2.  require ‘rubygems’
  3. require ‘xmlsimple’
  4. require ‘net/http’
  5.  
  6. class Tagger
  7.   def content
  8.     @content
  9.   end
  10.   def content=(content)
  11.     @content = content
  12.   end
  13.     def appid
  14.     @appid
  15.   end
  16.   def appid=(appid)
  17.     @appid = appid
  18.   end
  19.   def initialize
  20.  
  21.   end
  22.   def fetch
  23.           url = URI.parse(‘http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction’)
  24.       post_args = {
  25.             ‘appid’ => appid,
  26.             ‘context’ => content,
  27.             ‘output’ => "xml"
  28.       }
  29.       resp1, xml_data = Net::HTTP.post_form(url, post_args)
  30.       keywords = ""
  31.       data = XmlSimple.xml_in(xml_data)
  32.       data[‘Result’].each do |item|
  33.       keywords = keywords + item + ", "
  34.       end
  35.       return keywords
  36.   end
  37. end

Download the class here
Sample usage :

  1. require ‘tagger’
  2. tagg = Tagger.new
  3. tagg.appid =     ‘GO_GET_YOUR_OWN!’
  4. tagg.content = "The content of the post….."
  5. puts tagg.fetch

The appid is available from the Yahoo Developer Network
Limitations : Maximum 5000 queries per day per IP.

  1. 2 Responses to “Ruby class to fetch suggested keywords”

  2. By Martin DeMello on Aug 15, 2008 | Reply

    Ruby can autogenerate your getters and setters for you:

    class Tagger
    attr_accessor :content, :app_id

    Also, there is no need for an empty initialize method - just leave it out if you aren’t doing any initialization.

    Check out the String#join method too:

    keywords = data.join(”, “)

    doesn’t have the problem of an extraneous “,” after the last element.

  3. By Brian Cardarella on Aug 15, 2008 | Reply

    Instead of writing out the content/content= and appid/appid= methods Ruby has a cool shortcut:

    attr_accessor :content, :appid

    It will define the getter and setter methods as well as the instance variable at runtime, quicker than writing out that repetitive code.

Post a Comment