Skip to content

Adding Search to Sinatra

July 27, 2011

I was asked to add a search to an application that is written in java.
Initially I thought of implementing some of the search in java over hibernate, then I came up with another option.
All I wanted was a service that will expose the scoped search syntax and return the results as json. I tried running it as a Sinatra application, it turned out to be the following  short piece of code:

require 'sinatra'
require 'sinatra/activerecord'
require 'scoped_search'
require 'json'

set :database, 'postgresql://candlepin:candlepin@localhost/candlepin'
class Subscription < ActiveRecord::Base
  set_table_name 'cp_pool'
  belongs_to :organization, :foreign_key => :owner_id
  scoped_search :on => :productname, :complete_value => true, :rename => :product
  scoped_search :on => :activesubscription, :complete_value => {:true => true, :false => false}, :rename => :active
  scoped_search :on => :quantity, :complete_value => true
  scoped_search :on => :contractnumber, :complete_value => true, :rename => :contract
  scoped_search :on => :enddate, :complete_value => true, :rename => :expire
  scoped_search :on => :startdate, :complete_value => true, :rename => :begin
  scoped_search :in => :organization, :on => :displayname, :complete_value => true, :rename => :org

class Organization < ActiveRecord::Base
  set_table_name 'cp_owner'
  has_many :subscription

get '/subscriptions' do
  res = Subscription.search_for("#{params[:search]}")
  content_type :json

get '/subscriptions/auto_complete_search' do
  res = Subscription.complete_for("#{params[:search]}")
  content_type :json

That’s it. That is all the code I needed, in order to add search and auto-completer capabilities to a non-rails application.
Can it get any simpler then that?


From → Design, Developers

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: