I have known about JSONP for some time now but it didn’t really “click” with me until this week for some reason. Now… I think it is awesome!
So, How to enable JSONP support in a Rails app?
In a Rails controller where you want to return JSON to a callback function specified in an AJAX request, simple add a callback key and value (via param[:callback]) to the call to render json:
render :json => your_data_hash.to_json, :callback => params[:callback]
When the JSONP AJAX request is made and a callback is specified (via the ?callback= param OR the jsonpCallback option in jQuery’s $.ajax() function), Rails will now send back that JSON to the specified callback function in the DOM. Voila!
While this is sorta trivial, its a nice tool to have in the bag.
I’m always learning.
Here’s the story:
Imagine you have a mongodb Document, lets call it Parent.
Now lets imagine that a Parent has many Children so those Children are an embedded document within the Parent document. Great. All setup.
Now, suppose after you create a Child you want to run a callback, after_create, to give that child an eye color (ie something like :eye_color => “blue”).
Well, it turns out that embedded documents respond to their parents lifecycle instead of their own. So our after_create callback would only get run for the first born child… (first kids get everything, don’t they?) not cool.
My solution goes something like this…
In my Child model I now have:
class Child
include MongoMapper::EmbeddedDocument
embedded_in :parent
after_validation :color_eyes
def color_eyes
if self.updated_at
self.eye_color = “blue”
end
end
So the method color_eyes will only get run when a document has not been updated yet.
A hack, but its where I am right now. Any better ideas?? Let me know!
Rails templates in 2.3 seems to be VERY powerful… The idea that you can get a Rails template for a twitter app and almost instantly have a starting point for a twitter app/mashup is phenominal and will lead to a surge in creativity (i believe).