A Rack middleware for providing JSON-P support.
Full credit to Flinn Mueller (actsasflinn.com/) for this contribution.
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 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) response = pad(request.params.delete('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
Generated with the Darkfish Rdoc Generator 2.