Skip to content

Instantly share code, notes, and snippets.

@skamithi
Created April 25, 2012 14:53
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save skamithi/2490331 to your computer and use it in GitHub Desktop.
Save skamithi/2490331 to your computer and use it in GitHub Desktop.
Adding Opensearch to my Rails 3.2 app
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def opensearch
response.headers['Content-Type'] = 'application/opensearchdescription+xml; charset=utf-8'
end
#spec/controller/application_controller_spec.rb
require 'spec_helper'
describe ApplicationController do
describe 'GET "opensearch"' do
before do
xml_http_request :get, :opensearch
end
subject { response }
it { should render_template('application/opensearch') }
context 'header' do
subject { response.header['Content-Type'] }
it { should == 'application/opensearchdescription+xml; charset=utf-8' }
end
end
end
#app/helper/application_helper.rb
module ApplicationHelper
def full_image_path_helper(img)
root_url.chomp('/') + asset_path(img)
end
end
#app/views/application/opensearch.xml.builder
xml.instruct!
xml.OpenSearchDescription(:xmlns => 'http://a9.com/-/spec/opensearch/1.1/', 'xmlns:moz' => 'http://www.mozilla.org/2006/browser/search/') do
xml.ShortName(t(:default_title))
xml.InputEncoding('UTF-8')
xml.Description(t(:opensearch_description))
xml.Contact(t(:contact_email))
xml.Image(full_image_path_helper('icon.png'), height: 16, width: 16, type: 'image/png')
# escape route helper or else it escapes the '{' '}' characters. then search doesn't work
xml.Url(type: 'text/html', method: 'get', template: CGI::unescape(search_url(q: '{searchTerms}' )))
xml.moz(:SearchForm, root_url)
end
#spec/view/application/opensearch.xml.builder_spec.rb
require 'spec_helper'
describe "application/opensearch" do
before do
render
@xml_element = Nokogiri.XML rendered
end
context 'short name' do
subject { @xml_element.search('ShortName').text }
it { should == I18n.translate('default_title') }
end
context 'search description' do
subject { @xml_element.search('Description').text }
it { should == I18n.translate('opensearch_description') }
end
context 'input encoding ' do
subject { @xml_element.search('InputEncoding').text }
it { should == 'UTF-8' }
end
context 'contact email' do
subject { @xml_element.search('Contact').text }
it { should == I18n.translate('contact_email') }
end
context 'image' do
subject { @xml_element.search('Image').text }
it { should == 'http://test.host/assets/icon.png' }
end
context 'search terms' do
subject { @xml_element.search('Url').attr('template').value }
it { should == CGI.unescape(search_url(:q => '{searchTerms}')) }
end
end
@fred
Copy link

fred commented Apr 29, 2012

very useful gist, thanks a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment