Skip to content

Instantly share code, notes, and snippets.

@ngw
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngw/9091503 to your computer and use it in GitHub Desktop.
Save ngw/9091503 to your computer and use it in GitHub Desktop.
module WalterSobchak
class GoogleCustomSearch
def initialize
@client = Google::APIClient.new(
key: configatron.google.api_key, authorization: nil)
@search = @client.discovered_api('customsearch')
end
def execute(q)
[1, 11, 21].inject([]) do |result, num|
json = Oj.load(query(q, num).body)
result << json['items'] if json['error'].nil?
end.flatten
end
private
def query(q, num)
@client.execute(api_method: @search.cse.list,
parameters: {q: q, start: num,
key: configatron.google.api_key,
cx: configatron.google.custom_search_engine})
end
end
end
====
require 'spec_helper'
describe 'WalterSobchak::GoogleCustomSearch' do
before :each do
@fake_google_client = double('Google::APIClient')
@fake_search_api = double('Google::APIClient::API').as_null_object
@fake_result = double('Google::APIClient::Result').as_null_object
end
context 'at creation' do
it 'should have an APIClient available' do
Google::APIClient.should_receive(:new).with({
key: 'test_api_key', authorization: nil}).and_return(@fake_google_client)
@fake_google_client.should_receive(:discovered_api).with(
'customsearch').and_return(@fake_search_api)
WalterSobchak::GoogleCustomSearch.new
end
end
context 'when querying' do
it 'should execute a query' do
pending
Google::APIClient.should_receive(:new).with({
key: 'test_api_key', authorization: nil}).and_return(@fake_google_client)
@fake_google_client.should_receive(:discovered_api).with(
'customsearch').and_return(@fake_search_api)
@fake_google_client.should_receive(:execute).and_return(@fake_result)
Oj.should_receive(:load).and_return(@fake_result)
google_client = WalterSobchak::GoogleCustomSearch.new
google_client.execute('test')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment