Adding Search to Sinatra
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
end
class Organization < ActiveRecord::Base
set_table_name 'cp_owner'
has_many :subscription
end
get '/subscriptions' do
res = Subscription.search_for("#{params[:search]}")
content_type :json
res.to_json
end
get '/subscriptions/auto_complete_search' do
res = Subscription.complete_for("#{params[:search]}")
content_type :json
res.to_json
end
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?
Trackbacks & Pingbacks