class Rack::JSONP

A Rack middleware for providing JSON-P support.

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

Constants

U2029
VALID_CALLBACK
VALID_JS_VAR

Public Instance Methods

call(env) click to toggle source

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.

# File lib/rack/contrib/jsonp.rb, line 35
def call(env)
  request = Rack::Request.new(env)

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

  if STATUS_WITH_NO_ENTITY_BODY.include?(status)
    return status, headers, response
  end

  headers = HeaderHash.new(headers)
  
  if is_json?(headers) && has_callback?(request)
    callback = request.params['callback']
    return bad_request unless valid_callback?(callback)

    response = pad(callback, response)

    # No longer json, its javascript!
    headers['Content-Type'] = 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

Public Class Methods

new(app) click to toggle source
# File lib/rack/contrib/jsonp.rb, line 25
def initialize(app)
  @app = app
end