Skip to content

alexreisner/google_custom_search

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Google Custom Search

This project is a Ruby API to Google’s Custom Search Engine (www.google.com/cse).

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.

Install

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://github.com/alexreisner/google_custom_search.git

Configure

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:

GOOGLE_SEARCH_CX = "..."

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:

GOOGLE_SEARCH_PARAMS = {
  :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'

Use

To perform a search:

results = GoogleCustomSearch.search("Hank Aaron")

The results variable is now a GoogleCustomSearch::ResultSet object:

results.total            # 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
end

Future

  • 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

About

Ruby API to Google Custom Search Engine.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages