Skip to content

Instantly share code, notes, and snippets.

@anthonybishopric
Created May 28, 2011 19:43
Show Gist options
  • 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

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