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!)

1 total

Use Google's API to search your rails site

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.
1 total