class BackgroundImages::Finder
Attributes
find_image_of[RW]
max_attempts[RW]
results[RW]
Public Class Methods
new(find_image_of = "Brad Pitt's Ghost")
click to toggle source
# File lib/background_images/finder.rb, line 5 def initialize(find_image_of = "Brad Pitt's Ghost") @find_image_of = find_image_of @max_attempts = 3 end
Public Instance Methods
find_many(attempt=1)
click to toggle source
# File lib/background_images/finder.rb, line 10 def find_many(attempt=1) return results unless results.nil? if attempt > @max_attempts raise "Unable to get response from Google Image search" end response = JSON.parse(find_command) return find_many(attempt+1) unless valid_image_search_response?(response) results = response["responseData"]["results"] if results.empty? raise "Unable to get response from Google Image search" end return results end
find_one(method=:first)
click to toggle source
# File lib/background_images/finder.rb, line 30 def find_one(method=:first) result = find_many.send(method) return find_one if result.nil? return result end
Private Instance Methods
encode(query_string="")
click to toggle source
# File lib/background_images/finder.rb, line 49 def encode(query_string="") URI::encode(query_string) end
find_command()
click to toggle source
# File lib/background_images/finder.rb, line 41 def find_command `curl "#{find_url}"` end
find_url()
click to toggle source
# File lib/background_images/finder.rb, line 45 def find_url "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=#{encode(find_image_of)}" end
valid_image_search_response?(response)
click to toggle source
# File lib/background_images/finder.rb, line 37 def valid_image_search_response?(response) response.is_a?(Hash) && response.has_key?("responseData") && response["responseData"].is_a?(Hash) && response["responseData"].has_key?("results") end