Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Route resolver for Rails3 into Backbone-style routes
// 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]);
}
};
})();
# 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) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.