Skip to content

Instantly share code, notes, and snippets.

@mjrb
Last active June 27, 2019 04:24
Show Gist options
  • Save mjrb/acef1d079e73f3a1d8bf598d26c36f80 to your computer and use it in GitHub Desktop.
Save mjrb/acef1d079e73f3a1d8bf598d26c36f80 to your computer and use it in GitHub Desktop.
simple todo api using sinatra and mongoid.

Todo Api (exercise)

I haven't got much time to play around with new stuff lately so I decided to try out sinatra and mongoid. I've never used an ORM/ODM but I do like mongodb, and mongoid can remove some boilerplate. After working with a bunch of other languages that I like with varying degree, it felt like a breath of fresh air to go back to my ruby roots.

required gems (if i can remeber)

  • sinatra
  • sinatra-contrib
  • mongoid
require 'mongoid'
Mongoid.load!('./mongoid.yml', :development)
class Todo
include Mongoid::Document
field :text, type: String
field :done, type: Boolean, default: false
field :timeCreated, type: DateTime, default: ->{Time.now}
def as_json(options={})
attrs = super(options)
attrs["_id"] = attrs["_id"].to_s
attrs
end
end
development:
clients:
default:
database: todo-ruby
hosts:
- localhost:27017
require 'sinatra'
require 'sinatra/json'
require './model.rb'
set :port, 8080
before '/todo*' do
if request.body.length > 0
begin
@body = JSON.parse request.body.read
rescue
status 400
json error: "json expected"
end
end
end
helpers do
def body_require param
puts @body
unless @body.key? param
puts '#{param} missing'
halt 400, json(error: "parameter #{param} required")
end
end
end
set :show_exceptions, :after_handler
error Mongoid::Errors::DocumentNotFound do
halt 404
end
post '/todo' do
body_require 'text'
newTodo = Todo.create(text: @body['text'])
json newTodo
end
get '/todo' do
json Todo.all
end
get '/todo/:id' do
todo = Todo.find(params[:id])
json todo
end
put '/todo/:id' do
body_require 'newText'
todo = Todo.find(params[:id])
todo.set text: @body['newText']
json todo
end
patch '/todo/:id' do
todo = Todo.find(params[:id])
todo.set done: true
json todo
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment