Class: Faye::RackAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/faye/rack_adapter.rb

Constant Summary collapse

DEFAULT_ENDPOINT =
'/bayeux'
TYPE_JSON =
{'Content-Type' => 'text/json'}
TYPE_SCRIPT =
{'Content-Type' => 'text/javascript'}
TYPE_TEXT =
{'Content-Type' => 'text/plain'}

Instance Method Summary collapse

Constructor Details

#initialize(app = nil, options = nil) ⇒ RackAdapter

Returns a new instance of RackAdapter.



13
14
15
16
17
18
19
20
# File 'lib/faye/rack_adapter.rb', line 13

def initialize(app = nil, options = nil)
  @app      = app if app.respond_to?(:call)
  @options  = [app, options].grep(Hash).first || {}
  
  @endpoint = @options[:mount] || DEFAULT_ENDPOINT
  @script   = @endpoint + '.js'
  @server   = Server.new(@options)
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/faye/rack_adapter.rb', line 22

def call(env)
  request = Rack::Request.new(env)
  case request.path_info
  
  when @endpoint then
    message  = JSON.parse(request.params['message'])
    jsonp    = request.params['jsonp'] || JSONP_CALLBACK
    type     = request.get? ? TYPE_SCRIPT : TYPE_JSON
    response = nil
    
    @server.process(message, false) do |replies|
      response = JSON.unparse(replies)
      response = "#{ jsonp }(#{ response });" if request.get?
    end
    
    # TODO support Thin's async responses
    sleep(0.1) while response.nil?
    [200, type, [response]]
  
  when @script then
    [200, TYPE_SCRIPT, File.new(CLIENT_SCRIPT)]
  
  else
    env['faye.server'] = @server
    @app ? @app.call(env) :
           [404, TYPE_TEXT, ["Sure you're not looking for #{@endpoint} ?"]]
  end
end