views:

401

answers:

2

I am using Rails 2.3 and I decided to provide support for JSONP. Created a brand new application. Then ran script/generate scaffold User name:string

This is my entire environment.rb

RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
require File.join(File.dirname(__FILE__), 'boot')
require 'rack/contrib'
Rails::Initializer.run do |config|
 config.middleware.use 'Rack::JSONP'
end

When I visit localhost:3000/users all I get is a hash. When I visit localhost:3000/users.js?callback=show then I get good result.

Let's look at the jsonp code . I do not understand why response is being wrapped in an array.

I created another Rack middleware where I replaced this statement

      [status, headers, [response]]

with this statement

      [status, headers, response]

And now everything is working fine.

I refuse to believe that this is a bug in rack-contrib.

Can someone enlighten me why response is being wrapped in an array and how could I use rack-contrib in my application.

The full source code of my application is here. Just clone it and run on localhost:3000 .

+2  A: 

That code is wrong. Here's what it should be:

def call(env)
  status, headers, response = @app.call(env)
  request = Rack::Request.new(env)
  if request.params.include?('callback')
    response = [pad(request.params.delete('callback'), response)]
    headers['Content-Length'] = response.length.to_s
  end
  [status, headers, response]
end

It was incorrectly wrapping the response in an array in the case where the params didn't include a callback. The reason it needs to wrap the response in an array in the case where params does include a callback is because Rack responses must respond to .each().

Seth Yates
A: 

Here is an elaborated concept on how jsonp works. Hope it'll help you. JSONP First Timer

adnan