Created
June 6, 2011 10:45
-
-
Save stengland/1010063 to your computer and use it in GitHub Desktop.
Paginated google custom search using HTTParty, Will Paginate and Ostruct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'httparty' | |
require 'will_paginate/collection' | |
require 'ostruct' | |
class GoogleCustomSearch | |
include HTTParty | |
base_uri 'https://www.googleapis.com/customsearch/v1' | |
format :json | |
default_params :cx => 'google-costom-searck-id', :key => 'google-api-key' | |
def self.search(q = '', options = {}) | |
return [] if q.blank? | |
options[:page] ||= 1 | |
options[:per_page] ||= 10 | |
WillPaginate::Collection.create( options[:page], options[:per_page] ) do |pager| | |
response = get('', :query => { | |
:num => pager.per_page, | |
:start => ( ( pager.current_page - 1) * pager.per_page ) + 1, | |
:q => q | |
}) | |
puts response.inspect | |
pager.replace( response['items'].map{|t| OpenStruct.new(t) } ) | |
pager.total_entries = response['queries']['request'][0]['totalResults'] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment