Skip to content

Instantly share code, notes, and snippets.

@anthonybishopric
Created May 28, 2011 19:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonybishopric/997152 to your computer and use it in GitHub Desktop.
Save anthonybishopric/997152 to your computer and use it in GitHub Desktop.
Rails 3 routes in Javascript
<script type="text/javascript">
var __RouteCurry = function(route){
return function(options){
var routeMod = route;
if (typeof options == "string" || typeof options == "number"){
routeMod = routeMod.replace(/:[a-zA-Z0-9\_]+/,options);
}
else{
for(key in options){
routeMod = routeMod.replace(":"+key, options[key]);
}
}
routeMod = routeMod.replace(/\([^\(]*:[^\(]+\)/g,"");
routeMod = routeMod.replace(/\(|\)/g,"");
return routeMod;
}
};
var UrlFor = {
<%= raw ((ActionController::Routing::Routes.named_routes.names.map do |route|
"#{route} : __RouteCurry(#{ActionController::Routing::Routes.named_routes[route].path.to_json})"
end).join(",") )
%>
};
</script>
@anthonybishopric
Copy link
Author

This lets you to things like

UrlFor.people(1); // /people/1
UrlFor.people({id : 1}); // /people/1

and any other named routes your helpers already give you.

@anthonybishopric
Copy link
Author

Regex on line 13 won't work for all routes. Nested optional parameters will mess it up, for example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment