Friday, November 23, 2012

How to pass a Rails or Sinatra variable into JQuery.

A few days back I got a code challenge for a cool job position. For whatever reason the test was very light on Rails very heavy on JQuery, which I didn't know much about frankly. So in less than 24 hours I had to not only learn enough of it but also make it work into a modal window widget. I got it done, but it wasn't elegant at all. I clobbered it even if it worked.

The first challenge was to get information into webpage from a Rails application, I chose JSON and thought it'd be easy-peasy, but transferring a JSON object is a cross-domain script violation and most browsers won't let it pass. So I learned about JSONp which wraps the JSON object in a JQuery call-back. Lacking the easy Ruby ways of determining what things are, at first I'd no idea what the JSONP object was and just had my Rails app send JSON. Once I figured what it was, it was trivial to get Rails to do it. All I had to do was add: :callback => params[:callback] to the format property in the controller action. A JSONP basically sends a JS object to the server, and then gets it back with your nifty little JSON object inside of it. Because it's the object you sent that comes back, it provides some security as it's not just any input that can come on in.

The real challenge was in learning JQuery which is has a completely different documentation from Ruby and one that's less readable, I think. I wrote it in CoffeeScript which I prefer, but that is no shortcut for learning the JQuery functions. On key thing to know, that doesn't seem obvious at all is that an Object's properties can't call a function, they can *be* a function that calls a function, but not call a function. So open : myfunc() doesn't work but open : -> myfunc() works perfectly fine.

So after (why is it always after) I submitted the code challenge, I found out that there is a JQuery UI that has a very pretty way of doing what I was trying to do. But now with my new found JQuery and Javascript know-how I was able to put it to go work and redid the widget using JQuery UI.

But, I wanted to make it better. I wanted the Sinatra Application hosting the JQuery widget to intelligently pass the url to the JQuery widget. And that's not as simple as it sounds, but it turns out there is a great gem that does exactly that and it's called gon and gon-sinatra.

For the Sinatra app all I needed was two lines:

require 'gon-sinatra' 
Sinatra::register Gon::Sinatra
and now I can set an instance variable to a gon method and then access it as a gon property on the JavaScript side.

Sinatra or erb view:
  gon.jsonp_url = @jsonp_url
CoffeeScript:
  $.ajax
    url: gon.jsonp_url


And voilá, now I can set the URL to get the JSON from different websites, maybe localhost in development and somewhere else in production. I'll put the code for the revised widget up on github soon.





No comments:

Post a Comment