Class: Rack::JSONP

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

Overview

A Rack middleware for providing JSON-P support.

Full credit to Flinn Mueller (actsasflinn.com/) for this contribution.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ JSONP

Returns a new instance of JSONP.



10
11
12
# File 'lib/rack/contrib/jsonp.rb', line 10

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object

Proxies the request to the application, stripping out the JSON-P callback method and padding the response with the appropriate callback format if the returned body is application/json

Changes nothing if no callback param is specified.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rack/contrib/jsonp.rb', line 20

def call(env)
  status, headers, response = @app.call(env)

  headers = HeaderHash.new(headers)
  request = Rack::Request.new(env)
  
  if is_json?(headers) && has_callback?(request)
    status, response = translate_error_code(status, response)
    response = pad(request.params.delete('callback'), response)

    # No longer json, its javascript!
    headers['Content-Type'].gsub!('json', 'javascript')
    
    # Set new Content-Length, if it was set before we mutated the response body
    if headers['Content-Length']
      length = response.to_ary.inject(0) { |len, part| len + bytesize(part) }
      headers['Content-Length'] = length.to_s
    end
  end
  [status, headers, response]
end