public
Last active

Route resolver for Rails3 into Backbone-style routes

  • Download Gist
router.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
// Router.js 0.1.0
// (c) 2011 Doc Ritezel
// Freely distributable under the MIT license.
//
// Load this before rails_routes.js (generated by routes_to_javascript.rb)
// Enables:
// var c = new Backbone.Controller({ routes: { Routes.root(): 'index' } });
// $('a.delete').attr('href', Routes.delete_item(3));
 
(function(){
var root = this;
var getParams = /(:([\w\d]+)|\*([\w\d]+))/g;
function Routes() {
this.routes = {};
}
root.Routes = new Routes();
root.Routes.url_for = function urlFor(name) {
return this.routes[name];
};
function router(pathMatch) {
var parts = pathMatch.match(getParams);
return function pathRouter() {
var i, l, p, sliced, args, path = pathMatch.toString();
if (arguments.length) {
if (typeof arguments[0] === 'object') {
args = arguments[0];
for (i = 0, l = parts.length, p = parts[i]; i < l; i++) {
sliced = p.slice(1);
if (args[sliced] !== undefined) {
path = path.replace(p, args[sliced]);
}
}
} else {
args = Array.prototype.slice.call(arguments);
for (i = 0, l = parts.length, p = parts[i]; i < l; i++) {
if (args[i] !== undefined) {
path = path.replace(p, args[i]);
}
}
}
}
return path;
};
}
root.Routes.add_routes = function addRoutes(routes) {
var name;
for (name in routes) {
this.routes[name] = routes[name];
this[name + "_path"] = router(routes[name]);
}
};
})();
routes_to_javascript.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# drop into config/initializers
 
Rails.application.reload_routes!
routes_path = File.expand_path('public/javascripts/rails_routes.js', Rails.root)
all_routes = Rails.application.routes.routes.reject { |r| r.name.to_s == '' }
 
routes = all_routes.inject({}) do |memo, route|
memo[route.name] = route.path.sub('(.:format)', '')
memo
end
 
routes_template = <<ROUTES_TEMPLATE
(function() {
var routes = RAILS_ROUTES;
window.Routes.add_routes(routes);
})();
ROUTES_TEMPLATE
 
File.open(routes_path, 'w') {|f| f.write routes_template.sub('RAILS_ROUTES', routes.to_json) }

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.