Skip to content

Instantly share code, notes, and snippets.

@aler
Created April 23, 2009 02:50
Show Gist options
  • Save aler/100255 to your computer and use it in GitHub Desktop.
Save aler/100255 to your computer and use it in GitHub Desktop.
# isurvey simple server
require 'rubygems'
require 'sinatra'
require 'activerecord'
configure do
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => 'isurvey.sqlite3')
begin
ActiveRecord::Schema.define do
create_table :answers do |t|
t.text :name, :null => false
t.text :answer
t.timestamps
end
end
rescue ActiveRecord::StatementInvalid
# Do nothing, since the schema already exists
end
end
class Answer < ActiveRecord::Base
named_scope :recent, {:limit => 10, :order => 'updated_at DESC'}
end
before do
content_type "text/json"
end
get '/counter' do
{:counter => '2856',
:top_country => "USA",
:top_sex => "Male",
:top_gadget => "iPhone 3G" }.to_json
end
get '/surveys' do
{:surveys => ['Do you like Obama?']}.to_json
end
post '/answers' do
answer = Answer.new
answer.from_json(request.body.string)
if answer.save
status(201)
response['Number'] = answer.id.to_s
"Created answer #{answer.id} with text \"#{answer.name}\"\n"
else
status(412)
#response['Error'] = answer.errors.to_json
"Error: Cannot save answer\n"
end
end
get '/answers' do
answers = Answer.recent.all
answers.to_json
end
error ActiveRecord::RecordNotFound do
status(404)
@msg = "Answer not found\n"
end
not_found do
status(404)
@msg || "iSurvey doesn't know about that!\n"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment