Class: Rack::JSONP

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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ JSONP

Returns a new instance of JSONP.



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

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rack/jsonp.rb', line 12

def call(env)
  request = Rack::Request.new(env)
  requesting_jsonp = Pathname(request.env['PATH_INFO']).extname =~ /^\.jsonp$/i
  callback = request.params['callback']

  return [400,{},[]] if requesting_jsonp && !self.valid_callback?(callback)

  if requesting_jsonp
    env['PATH_INFO'] = env['PATH_INFO'].sub(/\.jsonp/i, '.json')
    env['REQUEST_URI'] = env['PATH_INFO']
  end

  status, headers, body = @app.call(env)

  if requesting_jsonp && self.json_response?(headers['Content-Type'])
    json = ""
    body.each { |s| json << s }
    body = ["#{callback}(#{json});"]
    headers['Content-Length'] = Rack::Utils.bytesize(body[0]).to_s
    headers['Content-Type'] = headers['Content-Type'].sub(/^[^;]+(;?)/, "#{MIME_TYPE}\\1")
  end

  [status, headers, body]
end