rabl icon indicating copy to clipboard operation
rabl copied to clipboard

enable_json_callbacks breaks caching

Open pwim opened this issue 10 years ago • 2 comments

If you use the enable_json_callbacks option, the callback itself is cached:

For example, if I call /api/1?callback=foo it will return foo({}), and subsequently /api/1 and /api/1?callback=bar will also return foo({}).

I took a brief look into fixing it in RABL, but it looks like the way caching is done will need to be rewritten to fix this, as the cache_results would need to be called from the to_* methods.

For my application, I am working around it by doing the following:

s = render_to_string("show.rabl")
if params[:callback]
  render js: "#{params[:callback]}(#{s})"
else
  render json: s
end

(when doing a json callback, the content type should be set to javascript, as reported in #547)

pwim avatar Apr 28 '14 05:04 pwim

Thanks for reporting this Paul.

nesquena avatar Apr 28 '14 08:04 nesquena

What I am doing is a slight variation:

#config/initializers/rabl.rb
# config.enable_json_callbacks = true

#app/controllers/application_controller.rb
after_filter :set_jsonp_format

def set_jsonp_format
  if params[:callback] && request.get?
    self.response_body = "#{params[:callback]}(#{response.body})"
    headers["Content-Type"] = 'application/javascript'
  end
end

The code is from here: https://github.com/spree/spree/blob/master/api/app/controllers/spree/api/base_controller.rb

mfenner avatar Sep 14 '14 11:09 mfenner