Skip to content

Instantly share code, notes, and snippets.

@stengland
Created June 6, 2011 10:45
Show Gist options
  • Save stengland/1010063 to your computer and use it in GitHub Desktop.
Save stengland/1010063 to your computer and use it in GitHub Desktop.
Paginated google custom search using HTTParty, Will Paginate and Ostruct
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