Skip to content

Instantly share code, notes, and snippets.

@renatosousafilho
Created August 29, 2012 14:29
Show Gist options
  • Save renatosousafilho/3513403 to your computer and use it in GitHub Desktop.
Save renatosousafilho/3513403 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'sinatra'
require 'sinatra/cross_origin'
require 'active_record'
require 'json'
require 'yajl'
require 'rack/cors'
ActiveRecord::Base.include_root_in_json = false
ActiveRecord::Base.establish_connection(
:adapter => 'mysql2',
:database => 'autofood_web_development',
:username => 'root',
:password => 'root'
)
class Category < ActiveRecord::Base
end
class Product < ActiveRecord::Base
end
class Service < ActiveRecord::Base
end
class Request < ActiveRecord::Base
end
set :protection, except: :json_csrf
before do
headers \
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => %w{GET POST PUT DELETE OPTIONS}.join(','),
'Access-Control-Allow-Headers' => %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(',')
params['model'] = Yajl::Parser.parse request.body || {}
end
configure do
enable :cross_origin
end
options '/services*' do
200
end
options '/requests*' do
# 200
end
get '/categories' do
content_type :json
@categories = Category.all
@categories.to_json
end
get '/categories/:id' do
content_type :json
@categories = Category.find(params[:id])
@categories.to_json
end
get '/categories/:id/products' do
content_type :json
@products = Product.where('category_id=?',params[:id])
@products.to_json
end
get '/services' do
content_type :json
Service.all.to_json
end
post '/services' do
service = Service.new(params['model'])
service.save
end
post '/requests' do
request = Request.new(params['model'])
request.save
end
get '/services/:id' do
content_type :json
@service = Service.find(params[:id])
@service.to_json
end
get '/services/:id/requests' do
content_type :json
@requests = Request.where('service_id=?',params[:id])
@requests.to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment