Sha256: e2e5ea90f5cf8ce6f1d96cf85ec6a3097f7d55eb743a08cf90afc1c4d04389f4

Contents?: true

Size: 1.88 KB

Versions: 1

Compression:

Stored size: 1.88 KB

Contents

require 'open-uri'
require 'rexml/document'

##
# Abstract class for implementing Yahoo APIs.
#
# http://developer.yahoo.com/

class Yahoo

  ##
  # Yahoo error class.

  class Error < RuntimeError; end

  ##
  # Web services initializer.
  #
  # The +appid+ is the Application ID that uniquely identifies your
  # application.  See: http://developer.yahoo.com/faq/index.html#appid
  #
  # Concrete web services implementations need to set the following instance
  # variables then call super:
  #
  # +host+:: API endpoint hostname
  # +service_name+:: service name
  # +version+:: service name version number
  # +method+:: service method call
  #
  # See http://developer.yahoo.com/search/rest.html

  def initialize(appid)
    @appid = appid
    @url = URI.parse "http://#{@host}/#{@service_name}/#{@version}/#{@method}"
  end

  ##
  # Extracts and raises an error from +obj+.  Returns if no error could be
  # found.

  def check_error(obj)
    obj = REXML::Document.new obj.read unless REXML::Document === obj

    err = obj.elements['Error']
    raise Error, err.elements['Message'].text if err
  end

  ##
  # Performs a GET request with +params+.  Calls the parse_response method on
  # the concrete class with an REXML::Document instance and returns its
  # result.

  def get(params)
    url = make_url params

    url.open do |xml|
      res = REXML::Document.new xml.read

      check_error res

      return parse_response(res)
    end
  rescue OpenURI::HTTPError => e
    check_error e.io
    raise
  end

  ##
  # Creates a URL from the Hash +params+.  Automatically adds the appid and
  # sets the output type to 'xml'.

  def make_url(params)
    params[:appid] = @appid
    params[:output] = 'xml'

    escaped_params = params.sort_by { |k,v| k.to_s }.map do |k,v|
      "#{URI.escape k.to_s}=#{URI.escape v.to_s}"
    end

    url = @url.dup
    url.query = escaped_params.join '&'
    return url
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
yahoo-1.0.0 lib/yahoo.rb