Question

I'm using visionmedia google search library for Ruby and I cannot find a way to choose the number of results in my search. I had a look at altering the search.size option from :large to :small but it didn't seem to make any difference. How would I limit the results to just five URLS.

require "google-search"

uris=[]
i=0

Google::Search::Web.new do |search|
    i = i + 1
    next if i == 6 
    search.query = "where is peru?"
    search.size = :small
    puts i
end.each_item { |item|  uris << item.uri }

print uris
Was it helpful?

Solution

This:

search = Google::Search::Web.new do |search|
  search.query = "where is peru?"
  search.size = :small
end

Creates a lazy enumerable object which only retrieves search results as you enumerate over them. Therefore this:

search.first(5)

Gets the first five searches; and this:

uris = search.first(5).map(&:uri)

Gets the first five uri's.

Change first(5) to first(20) and you'll see it take much longer to execute, which is consistent with the enumeration being lazy.

OTHER TIPS

One way would be to look at this method on line 183 of google-search/lib/google-search/search/base.rb

def self.size_for sym
      { :small => 4,
        :large => 8 }[sym]
    end

You could expand this hash and whatever custom search size you want.

Or, dig deep and see if you can eliminate it all together and allow new search options to accept ints for search.size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top