Skip to content

Instantly share code, notes, and snippets.

@rkh
Forked from mattetti/rack_example.ru
Created December 8, 2011 16:16
Show Gist options
  • Save rkh/1447468 to your computer and use it in GitHub Desktop.
Save rkh/1447468 to your computer and use it in GitHub Desktop.
Very basic sinatra application showing how to use a router based on the uri and how to process requests based on the HTTP method used.
#########################################
# Very basic sinatra application showing how to use a router based on the uri
# and how to process requests based on the HTTP method used.
#
# Usage:
# $ ruby rack_example.rb
#
# $ curl -X POST -d 'title=retire&body=I should retire in a nice island' localhost:4567/ideas
# $ curl -X POST -d 'title=ask Satish for a gift&body=Find a way to get Satish to send me a gift' localhost:4567/ideas
# $ curl localhost:9292/ideas
#
#########################################
class Idea
attr_accessor :title, :body, :created_at
# Memory store, gets cleared as the process is restarted
def self.store
@ideas ||= []
end
class InvalidParams < StandardError; end
# create an instance based on some passed params
def initialize(params)
raise InvalidParams, "You need to provide at least a title" unless params['title']
self.title = params['title']
self.body = params['body']
self.created_at = Time.now
end
# Converts an instance into a string
def to_s
"#{title} at #{created_at.to_s}\n#{body}"
end
end
require 'sinatra'
post('/ideas') { "Added, currently #{Idea.store.size} ideas are in memory!" if Idea.store << Idea.new(request.params) }
get('/ideas') { Idea.store.map{|idea, idx| idea.to_s }.join("\n\n") + "\n" }
error(Idea::InvalidParams) { |error| [400, error.message] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment