Skip to content

Instantly share code, notes, and snippets.

@Oshuma
Forked from igrigorik/webapp.rb
Created November 16, 2010 01:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Oshuma/701304 to your computer and use it in GitHub Desktop.
Save Oshuma/701304 to your computer and use it in GitHub Desktop.
require 'rubygems' if RUBY_VERSION =~ /1\.8/
require 'rack'
require "#{File.dirname(__FILE__)}/webapp"
if __FILE__ == $0
def usage
STDERR.puts("Usage: #{$0} <webrick, thin, mongrel>")
exit
end
def starting(app, server)
STDOUT.puts("Starting: '#{app.inspect}' with '#{server}'")
end
usage if ARGV.empty?
handler = ARGV.first
app = [].to_web_app
options = { :Port => 9292 }
case handler
when 'webrick'
starting(app, 'webrick')
Rack::Handler::WEBrick.run(app, options)
when 'thin'
starting(app, 'thin')
Rack::Handler::Thin.run(app, options)
when 'mongrel'
starting(app, 'mongrel')
Rack::Handler::Mongrel.run(app, options)
else
usage
end
end
module Rack
# Turn any object into a Rack app.
#
# class Array
# include Rack::ObjectApp
# end
#
# run Array.new.to_rack_app
module ObjectApp
# Return +self+ as a Rack app.
def to_rack_app
class << self
define_method(:call) do |env|
func, *attrs = env['PATH_INFO'].split('/').reject(&:empty?)
[ 200, { 'Content-Type' => 'text/html' }, send(func, *attrs) ]
end
end
self
end
end
end
require 'rubygems'
require 'rack'
class Object
def webapp
class << self
define_method :call do |env|
func, *attrs = env['PATH_INFO'].split('/').reject(&:empty?)
[200, {}, send(func, *attrs)]
end
end
self
end
end
# Rack::Handler::Mongrel.run [].webapp, :Port => 9292
# ^^^^^^^^^^^
# | (x)
# ROFLSCALE DB ---/
#
# http://localhost:9292/push/1 -> 1
# http://localhost:9292/push/2 -> 12
# http://localhost:9292/push/3 -> 123
# http://localhost:9292/to_a -> 123
# http://localhost:9292/pop -> 3
# http://localhost:9292/shift -> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment