public
Description: My Montreal on Rails 7 presentation of Thin
Homepage: http://www.montrealonrails.com/2008/01/22/announcing-mor-7-presenters-that-was-fast/
Clone URL: git://github.com/macournoyer/mor7.git
macournoyer (author)
Wed Feb 20 11:01:31 -0800 2008
commit  ef4721aaf5b2717610675c092ce0e166199642f8
tree    6898fe2dfe2ea9e37057d38e11f024d328d3f090
parent  550e63a97ea75df8b32c3d2e0dc625519282d613
mor7 / demo.rb
100644 58 lines (45 sloc) 1.367 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
%w(rubygems eventmachine thin thin_parser rack rack/lobster).each { |f| require f }
 
class Connection < EventMachine::Connection
  attr_accessor :app
  
  def initialize
    @parser = Thin::HttpParser.new
    @data = ''
    @nparsed = 0
    @env = {}
  end
  
  def receive_data(data)
    @data << data
    @nparsed = @parser.execute(@env, @data, @nparsed)
    
    process if @parser.finished?
  end
  
  def process
    status, headers, body = @app.call(@env)
    
    body_output = ''
    body.each { |l| body_output << l }
    
    send_data "HTTP/1.1 #{status} OK\r\n" +
              headers.inject('') { |h, (k,v)| h += "#k: #v\r\n" } +
              "\r\n" +
              body_output
    
    close_connection_after_writing
  end
end
 
welcome_app = proc do |env|
  [
    200, # Status
    {'Content-Type' => 'text/html'}, # Headers
    [
      '<html><body>',
      '<h1>Welcome</h1>',
      '<p>Welcome to my server!</p>', # Body
      '<p><a href="/rails">My Rails app!</a></p>',
      '</body></html>'
    ]
  ]
end
 
rails_app = Rack::Adapter::Rails.new(:root => '/Users/marc/projects/refactormycode', :prefix => '/rails')
 
app = Rack::URLMap.new('/' => welcome_app, '/rails' => rails_app)
 
EventMachine.run do
  EventMachine.start_server '0.0.0.0', 3000, Connection do |con|
    con.app = app
  end
end