Last active
December 23, 2016 05:36
-
-
Save mopsled/4470596 to your computer and use it in GitHub Desktop.
Simple Sinatra/ActiveRecord RESTful API
This file contains hidden or 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 'active_record' | |
class Color < ActiveRecord::Base | |
end |
This file contains hidden or 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 'active_record' | |
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => 'colors.db') | |
ActiveRecord::Schema.define do | |
create_table :colors do |t| | |
t.column :name, :string | |
t.column :description, :string | |
t.column :value, :string | |
end | |
end |
This file contains hidden or 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 'active_record' | |
require "./color.rb" | |
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => 'colors.db') | |
ActiveRecord::Base.include_root_in_json = false | |
get '/colors' do | |
Color.all.to_json | |
end | |
get '/color/:id' do | |
Color.where(:id => params['id']).first.to_json | |
end | |
post '/color' do | |
if params.has_key?('name') and params.has_key?('description') and params.has_key?('value') | |
newColor = Color.new(:name => params['name'], | |
:description => params['description'], | |
:value => params['value']) | |
newColor.save | |
end | |
end | |
put '/color/:id' do | |
selectedColor = Color.where(:id => params['id']).first | |
if selectedColor | |
if params.has_key?('name') | |
selectedColor.name = params['name'] | |
end | |
if params.has_key?('description') | |
selectedColor.description = params['description'] | |
end | |
if params.has_key?('value') | |
selectedColor.value = params['value'] | |
end | |
selectedColor.save | |
end | |
end | |
delete '/color/:id' do | |
Color.where(:id => params['id']).destroy_all | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment