Class: Goliath::Rack::JSONP

Inherits:
Object
  • Object
show all
Defined in:
lib/goliath/rack/jsonp.rb

Overview

A middleware to wrap the response into a JSONP callback.

Examples:

use Goliath::Rack::JSONP

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ JSONP

Returns a new instance of JSONP.



9
10
11
# File 'lib/goliath/rack/jsonp.rb', line 9

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/goliath/rack/jsonp.rb', line 13

def call(env)
  async_cb = env['async.callback']

  env['async.callback'] = Proc.new do |status, headers, body|
    async_cb.call(post_process(env, status, headers, body))
  end
  status, headers, body = @app.call(env)
  post_process(env, status, headers, body)
end

#post_process(env, status, headers, body) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/goliath/rack/jsonp.rb', line 23

def post_process(env, status, headers, body)
  return [status, headers, body] unless env.params['callback']

  response = ""
  if body.respond_to?(:each)
    body.each { |s| response << s }
  else
    response = body
  end

  [status, headers, ["#{env.params['callback']}(#{response})"]]
end