Skip to content

Instantly share code, notes, and snippets.

@dummied
Created April 9, 2015 00:40
Show Gist options
  • Save dummied/2821b52294c0217cde56 to your computer and use it in GitHub Desktop.
Save dummied/2821b52294c0217cde56 to your computer and use it in GitHub Desktop.
indy.rb Notes API in Sinatra
require 'bundler/setup'
require 'sinatra'
require 'mongoid'
require 'json'
Mongoid.load!("./mongoid.yml")
before do
content_type :json
end
get '/:version/notes' do
Note.all.to_json
end
get '/:version/notes/:note_id' do
@note = Note.find(params[:note_id])
if @note.nil?
status 404
{error: "The requested note does not exist"}.to_json
else
@note.to_json
end
end
post '/:version/notes' do
note = Note.new(params[:note])
if note.save
note.to_json
else
status 400
{:error => note.errors}.to_json
end
end
post '/:version/notes/:note_id' do
@note = Note.find(params[:note_id])
if @note.nil?
status 404
{error: "The requested note does not exist"}.to_json
else
@note.update_attributes(params[:note])
@note.to_json
end
end
post '/:version/notes/:note_id/destroy' do
@note = Note.find(params[:note_id])
if @note.nil?
status 409
{error: "This note is already deceased. Please stop kicking it, fine sir."}.to_json
else
@note.destroy
{:success => "Said note#{Note.destroyed_notes.sample}."}.to_json
end
end
class Note
include Mongoid::Document
field :subject, type: String
field :body, type: String
validates_presence_of :subject, :body
def self.destroyed_notes
[
" has shuffled off this mortal coil",
" is pushing up daisies",
" is pining for the fjords",
" has ceased to be",
" is no more",
" is a stiff",
" is bereft of life",
" rests in piece",
"'s metabolic processes are now history",
" is off the twig",
" has kicked the bucket",
" has run down the curtain",
" has joined the choir invisible",
" is an ex-parrot"
]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment