Skip to content

Instantly share code, notes, and snippets.

@antarestrader
Created November 22, 2008 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save antarestrader/27949 to your computer and use it in GitHub Desktop.
Save antarestrader/27949 to your computer and use it in GitHub Desktop.
Example of a Rack application that takes advantage to body.each to simulate a real-time data feed.
# Example of a Rack application that takes advantage to body.each to simulate
# a real-time data feed.
#
# Anyone may use this code AT YOUR OWN RISK.
require 'rack'
require 'ebb'
#This class simulates a server waiting for events. it will yield a line with one of the HTTP Request
#headers every half second. If things work right you should see you browser window slowely fill with
#request header lines as they are sent from the server.
class SlowIndex
def initialize(env)
@r = env.map{ |k,v| "#{k} => #{v}\n"}.sort
end
def each
#This should be relpaced with real magic. Anything yielded to the block will go out on the line.
@r.each do |i|
yield i
sleep 0.5
end
end
end
#Our actual Rack application Ezra and David can both eat my shorts. It is 0.007KLoC counting the
#coments. :)
class Server
def call(env)
[200, {"Content-Type" => "text/plain"}, SlowIndex.new(env)]
end
end
#There is Rack Middle ware to do this but it was faster to role my own then read the RDocs.
class Observer
def initialize(app)
@app = app
end
def call(env)
puts "Serving #{env['PATH_INFO']}"
status, headers, body = @app.call(env)
puts " #{status}"
[status, headers, body]
end
end
#We are going to try to serve files if tey exist so we can make Ajax Requests.
#!!!Warning - This is a great way to comprimized the securty of a production server. Always use
#Absolute Path names when not playing around.
app = Rack::Cascade.new([])
app << Rack::File.new('public/') # Serve Files from the public directory.
app << Server.new #Run our Micro App
s = Rack::Handler::Ebb #Ebb is much more friendly about sending out partial pages then Mongrel.
puts "** Starting Server **"
s.run(Observer.new(app), :Host=>'localhost', :Port=>4000)
puts "** Stopping Server **"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment