Class: Rack::JSONP::Callback

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

Instance Method Summary collapse

Constructor Details

#initialize(app, callback_param = "_callback") ⇒ Callback

Returns a new instance of Callback.



5
6
7
# File 'lib/rack/jsonp/callback.rb', line 5

def initialize(app, callback_param = "_callback")
  @app, @callback_param = app, callback_param
end

Instance Method Details

#call(env) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/rack/jsonp/callback.rb', line 9

def call(env)
  request = Rack::Request.new(env)

  if callback = request.params[@callback_param]
    # Save for underlying middlewares
    env["jsonp.callback"] = callback

    # Call original app
    status, headers, @body = @app.call(env)
    if headers["Content-Type"].to_s.start_with?("application/json")
      @pre, @post = "#{callback}(", ")"
      headers["Content-Length"] = (@pre.size + headers["Content-Length"].to_i + @post.size).to_s if headers["Content-Length"]
      headers["Content-Type"]   = "application/javascript" # Set proper content type as per RFC4329
      [200, headers, self]
    else
      [status, headers, @body]
    end
  else
    @app.call(env)
  end
end

#each(&block) ⇒ Object



31
32
33
34
35
# File 'lib/rack/jsonp/callback.rb', line 31

def each(&block)
  block.call(@pre)
  @body.each(&block)
  block.call(@post)
end