Skip to content

Instantly share code, notes, and snippets.

@owainlewis
Created February 4, 2014 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owainlewis/8807752 to your computer and use it in GitHub Desktop.
Save owainlewis/8807752 to your computer and use it in GitHub Desktop.
require 'sinatra'
require 'mongo'
require 'json/ext'
include Mongo
def connect!
begin
MongoClient.new("localhost", 27017)
rescue
puts "Failed to connect"
nil
end
end
configure do
conn = connect!
if conn
set :mongo_connection, conn
set :mongo_db, conn.db('clickdensity')
end
end
def as_json(data)
data.to_a.to_json
end
def click(mx, my, ww, wh, host, page, time_stamp, site_id, client_id)
{ mx: mx,
my: my,
ww: ww,
wh: wh,
host: host,
page: page,
ts: time_stamp,
sid: site_id,
cid: client_id }
end
def clicks
settings.mongo_db['clicks']
end
## Click Density API Routes
# All clicks
get '/' do
content_type :json
as_json(clicks.find)
end
# Find by site ID
get '/sites/:site_id' do
content_type :json
clicks = clicks.find(sid: params[:site_id])
as_json(clicks)
end
# Insert a click
get '/sites/:site_id/click' do
content_type :json
data = params[:data]
if data
new_click = click(10,10,10,10,"localhost", "/", Time.now, "123", "123")
result = clicks.insert(new_click)
status 200
result.to_json # return the BSON ID
else
status 401
"Bad request. Missing query param data"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment