mtrpcic.net Writing software since 1932

8May/111

Introducing js:routes – Your Rails Routes in JavaScript

I am a strong advocate of clear cut separation when it comes to code.  All JavaScript should be in one spot, should be easy to find, and should be easy to maintain.  Unfortunately, the built-in helpers that Rails provides for doing this (specifically in Rails 2.x.x) can blur my wonderful lines of separation, which is something that has bothered me since the dawn of time.  In addition to this, using the built-in helpers removes you from the nitty-gritty of the code being generated, making you less likely to truly understand what's happening, as well as making it much more difficult to modify it.

Because of the reasons above, I never use these built-in methods.  I much prefer a nice, clear cut separation for my scripts, and I'll handle the work myself.

application.js // Our document.ready wrapper
functions.js // Any utility functions we might want
extensions.js // any jQuery extensions we write
routes.js // All of our PathJS routes

I put all of my JavaScript in it's proper place, and it enjoys life there.  But there's one problem - one minor thing that has always bothered me about handling this myself...constructing URLs.  There has been many times where dragging an item from one location to another needs to make an AJAX call to update a "position" or a "parent_id".  Every time these calls are needed, you'll see some code like this:

$.ajax({
    url: "/books/" + book_id + "/pages/" + page_id,
    data: {
        "position":"top"
    },
    success: function(response){
        alert("Hazaa!");
    }
});

There is absolutely nothing elegant about the way that URL is being constructed.  Well, now there's a better way.

Say "Hello," to js:routes.

js:routes provides a simple rake task that will take all of your existing routes and convert them into JavaScript functions that take the appropriate parameters.

# Calling this will generate ./public/javascripts/rails_routes.js
rake js:routes

# You can name the file anything else by doing this
rake js:routes[other_file.js]

Now, you can tidy up those dirty constructed URL's.

// This...
url: "/books/" + book_id + "/pages/" + page_id

// Becomes this!
url: book_pages_path({"book_id": book_id, "id":page_id})

Everything is nice and tidy.  You can read more about it on the Github page.

Comments (1) Trackbacks (0)
  1. Looks pretty interesting, you might want to go into some details about how this fills in a gap for Rails developers where things like YUI Load Module (or similar) don’t cover off bringing sanity to URLs.

    Think about making a server-side-language agnostic version that can read from a JSON manifest or something, so all the people running node.js/clojure/php/asp/text can benefit too as long as they can write json code.


Leave a comment

(required)

No trackbacks yet.