“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay...”

Rob Lacey (contact@robl.me)
Senior Software Engineer, Brighton, UK

JSONP response in Rails Controller

If you’re used to rendering your JSON response via call to_json on a collection on an object then it really is as simple as adding the callback option to render. You must ensure the callback parameter on the client end is the correct parameter than you feed to the callback option in your controller. This allows your JSON to be server without or without wrapping the response with a callback function depending on whether you include the callback parameter.

class Api
  
  def index
    respond_to do |format|
        format.json do
          render :json => Thing.all.to_json, :callback => params[:callback]
        end
    end
  end

end

However, if you use JBuilder or any other JSON template engine then you’ll need to do things slightly differently. Here There is no need to change your controller method at but instead you can wrap the json repsonse in an after_filter which is a little cleaner.

class Api < ApplicationController

  after_filter :wrap_response_with_callback

  def index
    respond_to do |format|
        format.json
    end
  end

  private

  def wrap_response_with_callback
    if request.get? && params[:callback] && params[:format].to_s == 'json'
      response['Content-Type'] = 'application/javascript'
      response.body = "%s(%s)" % [params[:callback], response.body]
    end
  end

end