Note that it is technically incorrect to display JSON with a callback parameter, since you are receiving a JavaScript response (calling a JSON-P callback function), and not a JSON result. Therefore, if you have
render :json => my_object, :callback => params[:callback]
and the request will appear /users?callback=func , Rails will respond
func({β¦})
with the content type application/json , which is incorrect, since the above answer is clearly not JSON, but JavaScript.
The solution I am using is
def respond_with_json(item) respond_with do |format| format.json { render :json => item } format.js { render :json => item, :callback => params[:callback] } end end
which answers correctly with or without a callback. Applying this to the above solution, we get:
def custom_respond_with(*resources, &block) options = resources.extract_options! if params[:callback] old_block = block block = lambda do |format| old_block.call(format) if block_given? format.js { render :json => resources[0], :callback => params[:callback] } end end respond_with(*(resources << options), &block) end
Also, pay attention to the correction for resources[0] , otherwise you will end up wrapping the resources in an additional array as a result of the splat operator.
Ruben verborgh
source share