Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Use Google's API to search your rails site (See related posts)

Culled from various places on the 'net. This lets you use the Google API to do searching on your site. You'll need to get an API key from Google and abide by their usage terms etc. etc.

In search controller...

def search
 require 'soap/wsdlDriver'
 @title = 'Search Results'
 key = 'YOUR GOOGLE API KEY HERE'
 yoursite = 'YOUR SITE ADDRESS HERE'
 driver = SOAP::WSDLDriverFactory.new("http://api.google.com/GoogleSearch.wsdl").createDriver
 @results = driver.doGoogleSearch(key, @params['term']+" site:#{yoursite}", 0, 10, true, " ", false, " ", " ", " ")
end


The above expects to be called with a request parameter 'term' containing the actual search terms.

Then in your view (e.g. search.rhtml)...

<% for result in @results.resultElements %>
 <h2><%= result.title %></h2>
 <p><%= result.snippet %></p>
 <p><a href="<%= result.URL %>"><%= result.URL %></a></p>
<% end %>


Needs to be extended to handle paging the results but you get the idea.

Comments on this post

b-rad posts on Oct 11, 2006 at 13:58
google seemed to have some problems with the encoding. fixed by forcing UTF8:
$KCODE = "UTF8"

mtcodex posts on Oct 12, 2006 at 13:46
In the view to get the URL out you need to use the attribute accesor 'uRL' e.g.

<%= result.uRL %>
PLD posts on Aug 05, 2007 at 15:05
The above code would not work without the following change:

driver.generate_explicit_type = true

You need to create an account or log in to post comments to this site.