Skip to content

Instantly share code, notes, and snippets.

@dskecse
Forked from mattetti/rack_example.ru
Last active December 11, 2015 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dskecse/4647567 to your computer and use it in GitHub Desktop.
Save dskecse/4647567 to your computer and use it in GitHub Desktop.
#########################################
# Very basic rack application showing how to use a router based on the uri
# and how to process requests based on the HTTP method used.
#
# Usage:
# $ rackup config.ru
#
# $ curl -X POST -d 'title=retire&body=I should retire in a nice island' localhost:9292/ideas
# $ curl -X POST -d 'title=ask Satish for a gift&body=Find a way to get Satish to send me a gift' localhost:9292/ideas
# $ curl localhost:9292/ideas
#
# More info: https://github.com/rack/rack/wiki/Rack-app-with-uri-and-HTTP-specific-responses
#########################################
require './idea'
run IdeaAPI.new
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, self.body, self.created_at = params['title'], params['body'], Time.now
end
# Converts an instance into a string
def to_s; "#{title} at #{created_at.to_s}\n#{body}"; end
end
class IdeaAPI
def call(env)
case env['REQUEST_METHOD']
when 'POST'
Idea.store << Idea.new(request.params)
[200, {'Content-Type' => 'text/plain'}, ["Idea added, currently #{ Idea.store.size } ideas are in memory!"]]
when 'GET'
[200, {'Content-Type' => 'text/plain'}, [Idea.store.map { |idea, idx| idea.to_s }.join("\n\n") + "\n"]]
end if env['PATH_INFO'] == '/ideas'
[404, {}, ['Did you get lost?']]
rescue Idea::InvalidParams => error
[400, {'Content-Type' => 'text/plain'}, [error.message]]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment