Module: GoogleCustomSearchApi
- Extended by:
- GoogleCustomSearchApi
- Included in:
- GoogleCustomSearchApi
- Defined in:
- lib/version.rb,
lib/google_custom_search_api.rb
Defined Under Namespace
Classes: ResponseData
Constant Summary collapse
- VERSION =
"2.0.1"
Instance Method Summary collapse
-
#search(query, opts = {}) ⇒ Object
Search the site.
-
#search_and_return_all_results(query, opts = {}) ⇒ Object
Search the site for all available results (max 100).
Instance Method Details
#search(query, opts = {}) ⇒ Object
Search the site.
opts
see list here for valid options
http://code.google.com/apis/customsearch/v1/using_rest.html#query-params
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/google_custom_search_api.rb', line 18 def search(query, opts = {}) opts[:start] ||= 1 if (page = opts.delete(:page)) page = page.to_i opts[:start] = (page - 1).abs * 10 + 1 else page = (opts[:start].to_i / 10) + 1 end page = 10 if page > 10 # Get and parse results. url = url(query, opts) return nil unless results = fetch(url) results['items'] ||= [] # paging if results.keys.include?('queries') data = results['queries']['request'].first results['pages'] = data['totalResults'].to_i / 10 results['pages'] = 10 if results['pages'] > 10 results['current_page'] = page.to_i results['next_page'] = nil results['previous_page'] = nil if results['queries'].include?('nextPage') && page < 10 results['next_page'] = results['current_page'] + 1 end if page > 1 results['previous_page'] = page - 1 end end ResponseData.new(results) end |
#search_and_return_all_results(query, opts = {}) ⇒ Object
Search the site for all available results (max 100)
This isn’t so useful because it’s quite slow
Returns an array of up to 10 search(query) results
examples:
results = search_and_return_all_results(‘poker’) results.first.items.size # == 10
search_and_resturn_all_results(‘poker’) do |results|
results.items.size # == 10 10 times
end
search_and_return_all_results(
'"California cult winery known for its Rhône"') do |results|
results.items.size # == 3 1 time
end
opts
see list here for valid options
http://code.google.com/apis/customsearch/v1/using_rest.html#query-params
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/google_custom_search_api.rb', line 81 def search_and_return_all_results(query, opts = {}) res = [] opts[:start] ||= 1 begin results = GoogleCustomSearchApi.search(query, opts) return res unless results.keys.include?('queries') yield results if block_given? res << results if results.queries.keys.include?("nextPage") opts[:start] = results.queries.nextPage.first.startIndex else opts[:start] = nil end end while opts[:start].nil? == false return res end |