class PetClient

Public Class Methods

breed_list(animal) click to toggle source
# File lib/petsearch/petclient.rb, line 46
def self.breed_list(animal)
  begin
    raise ArgumentError if (@@token_hash[:expires].nil?  || @@token_hash[:expires] < Time.now )
    search_string = "#{ENV['PET_SECRET']}key=#{ENV['PET_KEY']}&animal=#{animal}&format=json&token=#{@@token_hash[:token]}"
    sig = Digest::MD5.hexdigest(search_string)
    url = "http://api.petfinder.com/breed.list?key=#{ENV['PET_KEY']}&animal=#{animal}&format=json&token=#{@@token_hash[:token]}&sig=#{sig}"
    updated_url = URI.encode(url)
    result = JSON.parse(open(updated_url.strip).read)
  rescue ArgumentError
     "Key Error.  Did you do PetClient.get_token(key, secret) or use PetClient.get_token with ENV variables?"
    return false
  end
end
build_url(search_string, random=nil, id=nil) click to toggle source

DRY-ish method for API lookup

# File lib/petsearch/petclient.rb, line 72
def self.build_url(search_string, random=nil, id=nil)
 begin
    sig = Digest::MD5.hexdigest(search_string)
    partial_string = search_string.scan(/key.*/)[0]
    if random && id.nil? == true
      url = "http://api.petfinder.com/pet.getRandom?"+ partial_string+"&sig=#{sig}"
    elsif !random && id.nil? == true
      url = "http://api.petfinder.com/pet.find?"+ partial_string+"&sig=#{sig}"
    else
      url = "http://api.petfinder.com/pet.get?"+ partial_string+"&sig=#{sig}"
    end
    updated_url = URI.encode(url)
  result = JSON.parse(open(updated_url.strip).read)
  raise NoMethodError if result['petfinder']['header']['status']['code']['$t'].to_i == 200
  raise NoRecordError if result['petfinder']['header']['status']['code']['$t'].to_i == 201
  result
 rescue NoMethodError
   return {'code' => '999', 'message' => "You typed in your options incorrectly"}
 rescue NoRecordError
   return {'code' => '201', 'message' => 'No results found'}
 rescue
   return {'code' => '999', 'message' => "Invalid token.  Did you do PetClient.get_token(key, secret) or use PetClient.get_token with ENV variables?" }
 end
end
get_pet(id) click to toggle source
# File lib/petsearch/petclient.rb, line 97
def self.get_pet(id)
  search_string = "#{ENV['PET_SECRET']}key=#{ENV['PET_KEY']}&id=#{id}&format=json&token=#{@@token_hash[:token]}"
  result = build_url(search_string, nil, id)
end
get_token(api_key=nil, api_secret=nil) click to toggle source
# File lib/petsearch/petclient.rb, line 24
def self.get_token(api_key=nil, api_secret=nil)
 begin
  key_status = 'bad' if ((api_key==nil ||  api_secret==nil) && (ENV['PET_SECRET']==nil || ENV['PET_KEY']==nil))
  raise BadKeyError, "API KEY ERROR" if key_status=='bad'
  key_secret =  (api_key.nil? || api_secret.nil?) ? ("#{ENV['PET_SECRET']}key=#{ENV['PET_KEY']}") : (api_secret+"key="+api_key)
  md5 = Digest::MD5.hexdigest(key_secret)
  @@token_hash = Hash.new
  @@token_hash[:md5] = md5
  @@token_hash[:time] = Time.now
  url = (api_key.nil? || api_secret.nil?) ? "http://api.petfinder.com/auth.getToken?key=#{ENV['PET_KEY']}&sig=#{@@token_hash[:md5]}" : "http://api.petfinder.com/auth.getToken?key=#{api_key}&sig=#{@@token_hash[:md5]}"
  updated_url = URI.encode(url)
  result = Nokogiri::XML(open(updated_url.strip).read)
  @@token_hash[:token] = result.xpath("//auth//token/text()").text.strip
  parsed_date = Time.at(result.xpath("//auth/expires/text()").text.strip.to_i)
  @@token_hash[:expires] = Time.parse(parsed_date.strftime('%a %d %b %Y %I:%M:%S %p'))
  puts ("Your token expires at #{@@token_hash[:expires]}")
  raise BadKeyError, "API KEY ERROR" if @@token_hash[:expires] < Time.now
  rescue
     "Re-check your keys"
  end
end
load_breeds(pet) click to toggle source

load all the breeds

# File lib/petsearch/petclient.rb, line 61
def self.load_breeds(pet)
  if breed_list(pet[:name]) == false
    puts("You have a key error")
  else
    pet[:breeds] = breed_list(pet[:name])['petfinder']['breeds']['breed'].map { |b|
        b["$t"]
   }
 end
end
new() click to toggle source
# File lib/petsearch/petclient.rb, line 17
def initialize
end
search_listings(options={}) click to toggle source
# File lib/petsearch/petclient.rb, line 102
def self.search_listings(options={})
  animal = (options[:animal].nil?) ? false : options[:animal]
  breeds = (options[:breeds].nil? || options[:breeds].empty?) ? "" : options[:breeds]
  size = options[:size].nil? ? "" : options[:size]
  sex = options[:sex].nil? ? "" : options[:sex]
  location = options[:location].nil? ? "" : options[:location]
  age = options[:age].nil? ? "" : options[:age]
  offset = options[:offset].nil? ? "" : options[:offset]
  count = options[:count].nil? ? "" : options[:count]
  random = (options[:random].nil? || options[:random]==false) ? false : true
  result_set = []

  # this is a custom option not supported by API
  distance = options[:distance].nil? ? "" : options[:distance]
  pure = options[:pure].nil? ? "" : options[:pure]

  ### must do loops if breed param
  if breeds && breeds!=""
    breeds.each { |breed|
      ## must have separate random search because do not want to pass in parameters that will break api call, even if empty strings
      if random
       search_string = "#{ENV['PET_SECRET']}key=#{ENV['PET_KEY']}&animal=#{animal}&size=#{size}&breed=#{breed}&sex=#{sex}&location=#{location}&output=full&format=json&token=#{@@token_hash[:token]}"
       result = build_url(search_string, random)
       result_set << result
      else
       search_string = "#{ENV['PET_SECRET']}key=#{ENV['PET_KEY']}&animal=#{animal}&size=#{size}&breed=#{breed}&sex=#{sex}&location=#{location}&age=#{age}&offset=#{offset}&count=#{count}&output=full&format=json&token=#{@@token_hash[:token]}"
       result = build_url(search_string)
       result_set <<  result
     end
    }
  else
    if random
      search_string = "#{ENV['PET_SECRET']}key=#{ENV['PET_KEY']}&animal=#{animal}&size=#{size}&sex=#{sex}&location=#{location}&output=full&format=json&token=#{@@token_hash[:token]}"
      result = build_url(search_string, random)
      result_set <<  result
    else
      search_string = "#{ENV['PET_SECRET']}key=#{ENV['PET_KEY']}&animal=#{animal}&size=#{size}&sex=#{sex}&location=#{location}&age=#{age}&offset=#{offset}&count=#{count}&output=full&format=json&token=#{@@token_hash[:token]}"
      result = build_url(search_string)
      result_set <<  result
    end
  end
  return result_set
end
token_hash() click to toggle source
# File lib/petsearch/petclient.rb, line 20
def self.token_hash
  @@token_hash
end