Class: Faye::RackAdapter

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

Defined Under Namespace

Classes: DeferredBody

Constant Summary collapse

ASYNC_RESPONSE =

Only supported under Thin

[-1, {}, []].freeze
DEFAULT_ENDPOINT =
'/bayeux'
SCRIPT_PATH =
File.join(ROOT, 'faye-client-min.js')
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.



18
19
20
21
22
23
24
25
# File 'lib/faye/rack_adapter.rb', line 18

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



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/faye/rack_adapter.rb', line 36

def call(env)
  request = Rack::Request.new(env)
  case request.path_info
  
  when @endpoint then
    begin
      message  = JSON.parse(request.params['message'])
      jsonp    = request.params['jsonp'] || JSONP_CALLBACK
      
      @server.flush_connection(message) if request.get?
      
      on_response(env, message) do |replies|
        response = JSON.unparse(replies)
        response = "#{ jsonp }(#{ response });" if request.get?
        response
      end
    rescue
      [400, TYPE_TEXT, 'Bad request']
    end
  
  when @script then
    [200, TYPE_SCRIPT, File.new(SCRIPT_PATH)]
  
  else
    env['faye.client'] = get_client
    @app ? @app.call(env) :
           [404, TYPE_TEXT, ["Sure you're not looking for #{@endpoint} ?"]]
  end
end

#get_clientObject



27
28
29
# File 'lib/faye/rack_adapter.rb', line 27

def get_client
  @client ||= Client.new(@server)
end

#run(port) ⇒ Object



31
32
33
34
# File 'lib/faye/rack_adapter.rb', line 31

def run(port)
  handler = Rack::Handler.get('thin')
  handler.run(self, :Port => port)
end