Created
May 29, 2013 22:12
-
-
Save mxlje/5674256 to your computer and use it in GitHub Desktop.
playing around with Sinatra & DataMapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra' | |
require 'data_mapper' | |
require 'json' | |
# Authentication | |
# use Rack::Auth::Basic, "Restricted Area" do |username, password| | |
# username == 'admin' and password == 'admin' | |
# end | |
# set json as content type for all requests | |
before do | |
content_type :json | |
end | |
DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/db.db") | |
class Order | |
include DataMapper::Resource | |
property :id, Serial | |
property :product, Text, :required => true | |
property :price, Float, :required => true | |
property :payed, Boolean, :required => true, :default => false | |
property :created_at, DateTime | |
property :updated_at, DateTime | |
end | |
DataMapper.finalize.auto_upgrade! | |
get '/' do | |
@orders = Order.all :order => :id.desc | |
@orders.to_json | |
end | |
get '/open' do | |
@orders = Order.all :payed => false | |
@orders.to_json | |
end | |
get '/new/:product/:price' do | |
o = Order.new | |
o.product = params[:product] | |
o.price = params[:price] | |
o.created_at = Time.new | |
o.updated_at = Time.new | |
@return = {} | |
if o.save | |
@return['status'] = 200 | |
@return['message'] = "Created Order ##{o.id}" | |
@return['order'] = o | |
else | |
@return['status'] = 400 | |
errors = [] | |
o.errors.each do |e| | |
errors << e | |
@return['errors'] = errors | |
end | |
end | |
@return.to_json | |
end | |
# show a specific order | |
get '/order/?:id?' do | |
@o = Order.get params[:id] | |
if @o | |
@o.to_json | |
else | |
'error'.to_json | |
end | |
end | |
# pay a product | |
get '/pay/:id' do | |
o = Order.get params[:id] | |
o.payed = true | |
o.updated_at = Time.new | |
o.save | |
"Payed Order ##{params[:id]}" | |
end | |
get '/delete_all' do | |
o = Order.all.destroy | |
redirect '/' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment