Module: GoogleCustomSearch

Extended by:
GoogleCustomSearch
Included in:
GoogleCustomSearch
Defined in:
lib/google_custom_search.rb

Overview

Add search functionality (via Google Custom Search). Protocol reference at: www.google.com/coop/docs/cse/resultsxml.html

Defined Under Namespace

Classes: Result, ResultSet

Instance Method Summary collapse

Instance Method Details

#search(query, offset = 0, length = 20) ⇒ Object

Search the site.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/google_custom_search.rb', line 21

def search(query, offset = 0, length = 20)
  
  # Get and parse results.
  url = url(query, offset, length)
  return nil unless xml = fetch_xml(url)
  data = Hash.from_xml(xml)['GSP']

  # Extract and return search result data, if exists.
  if data['RES']
    ResultSet.new(
      data['RES']['M'].to_i,                                  # total
      parse_results(data['RES']['R']),                        # pages
      data['SPELLING'] ? data['SPELLING']['SUGGESTION'] : nil # suggestion
    )
  else
    ResultSet.new(0, [], nil)
  end
end