Class: GoogleSearch

Inherits:
Object
  • Object
show all
Defined in:
lib/google-rest/google_search.rb

Constant Summary collapse

BASE_URL =
"http://ajax.googleapis.com/ajax/services/search"

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#cached_responseObject

Returns the value of attribute cached_response.



23
24
25
# File 'lib/google-rest/google_search.rb', line 23

def cached_response
  @cached_response
end

#cached_resultObject

Returns the value of attribute cached_result.



22
23
24
# File 'lib/google-rest/google_search.rb', line 22

def cached_result
  @cached_result
end

Instance Method Details

#search(options = {}) ⇒ Object

All you need to do is specify a :type => ‘web’ or :type => ‘local’ or whatever type of search you want to do. And you also need to pass a query through :q => “Awesomeness”. Any other optional parameters can be specified with a hash key value pair in the method call of search ie

search(:type => ‘web’, :q => ‘somequery’, :rsz => ‘big’) this would return a web search with the query ‘somequery’ and return a big resultset



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/google-rest/google_search.rb', line 33

def search(options = {})
  # Do a reverse_merge!, but since ruby doesn't have it built in do it like this
  # if I use it again I'll move reverse_merge into its own little extension library
  defaults = {:v => "1.0", :type => "web"}
  options.replace(defaults.merge(options))
  
  url = "#{BASE_URL}/#{options[:type]}?q=#{URI.encode(options[:q])}"
  
  options.delete(:type)
  options.delete(:q)
  
  options.each do |key, value|    
    url += "&#{key.to_s}=#{URI.encode(value.to_s)}"
  end
  url = URI.parse(url)
  
  @cached_response = Net::HTTP.get_response url
  @cached_result = JSON.parse(@cached_response.body)
  if @cached_result['responseStatus'] == 200
    return @cached_result['responseData']['results']
  else
    raise @cached_result['responseDetails']
  end
end