Class: Rack::JSONP
- Inherits:
-
Object
- Object
- Rack::JSONP
- Defined in:
- lib/rack/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
-
#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.
-
#initialize(app) ⇒ JSONP
constructor
A new instance of JSONP.
-
#pad(callback, response, body = "") ⇒ Object
Pads the response with the appropriate callback format according to the JSON-P spec/requirements.
Constructor Details
#initialize(app) ⇒ JSONP
Returns a new instance of JSONP.
9 10 11 |
# File 'lib/rack/jsonp.rb', line 9 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.
Changes nothing if no callback
param is specified.
18 19 20 21 22 23 |
# File 'lib/rack/jsonp.rb', line 18 def call(env) status, headers, response = @app.call(env) request = Rack::Request.new(env) response = pad(request.params.delete('callback'), response) if request.params.include?('callback') [status, headers, response] end |
#pad(callback, response, body = "") ⇒ Object
Pads the response with the appropriate callback format according to the JSON-P spec/requirements.
The Rack response spec indicates that it should be enumerable. The method of combining all of the data into a sinle string makes sense since JSON is returned as a full string.
32 33 34 35 |
# File 'lib/rack/jsonp.rb', line 32 def pad(callback, response, body = "") response.each{ |s| body << s } "#{callback}(#{body})" end |