Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
79 lines (44 sloc) 2.38 KB

Google Custom Search

This project is a Ruby API to Google's Custom Search Engine (

If you want a Google-like search engine for your web site, why not use Google? For $100/yr (more if you have over 1,000 pages) you can get access to Google search results for your site in XML format. The google_custom_search gem helps you access this web service and publish the results on your site however you like (all covered under Google's acceptable use policy).

Google Custom Search is currently compatible with Rails 2.x and Rails 3.


As a Gem

Add to your Gemfile:

gem "google_custom_search"

and run at the command prompt:

bundle install

Or As a Plugin

rails plugin install git://


You must define a constant in your application called GOOGLE_SEARCH_CX. For example, if you're using Rails, create a file config/initializers/google_custom_search.rb:


You can find the CX value for your custom search engine via the search control panel on Google's site (click the “Get code” link and you'll see a hidden “cx” field in the sample HTML form).

Optionally, you can set default Google search params, such as encoding, by setting up the GOOGLE_SEARCH_PARAMS hash in the same initializer:

  :ie => 'utf8',
  :oe => 'utf8'

If you're working outside of Rails you'll also need some require statements:

require 'rubygems'
require 'rexml/document'
require 'google_custom_search'


To perform a search:

results ="Hank Aaron")

The results variable is now a GoogleCustomSearch::ResultSet object:            # number of results (integer)
results.pages            # array of result objects
results.suggestion       # suggested search term, if any

Iterate through the results:

results.pages.each do |result|
  result.title           # result title
  result.url             # result URL
  result.description     # excerpt, with terms highlighted


  • prevent NameError when GOOGLE_SEARCH_CX is missing: show nice msg

  • access to all data returned by Google

  • support for features of CSE free version

  • support for multiple CSEs in one app (GOOGLE_SEARCH_CX should be a hash)

Copyright © 2009-11 Alex Reisner, released under the MIT license