Productively Distracted
Posted Sunday August 5, 2012 around 9:57 PM

JSONP is short for "JSON with padding". You can read about it more here. I recently needed to use JSONP with a project and I saw a request for the same thing on the jbuilder project, so I created jpbuilder. JPbuilder is built on top of Jbuilder. You use the same exact DSL for creating the JSON, but you use .jpbuilder as the template extension instead.


Install in your gem file and then just create templates with the extension .jpbuilder and use the normal Jbuilder DSL. The template will use the callback as specified in the "callback" url parameter. If none is provided then the regular JSON format will be returned.

Setting a default callback

You can set a global callback to be used in the absence of a callback listed in the params hash, by setting the JPbuilderHandler.default_callback variable in an initializer:

# config/initilizers/jpbuilder.rb
JPbuilderHandler.default_callback = "myJsCallback"

To disable the auto callback simply set JPbuilderHandler.default_callback to null or "".

# config/initilizers/jpbuilder.rb
JPbuilderHandler.default_callback = nil

Note: nil is the default value.


I hope that in the future this can somehow be merged into the jbuilder core. However as of today, the project seems dead (20+ issues and last commit almost 5 months ago), so I am not going to put the effort into a pull request just yet.


Edit 10/01/2012: The jbuilder project seems to be alive and well again. I will submit a patch soonish.

blog comments powered by Disqus