Skip to content

Instantly share code, notes, and snippets.

@andriytyurnikov
Created May 3, 2011 12:55
Show Gist options
  • Save andriytyurnikov/953275 to your computer and use it in GitHub Desktop.
Save andriytyurnikov/953275 to your computer and use it in GitHub Desktop.
Expose rails routes to javascript. Improve this stuff and get beer from me ;)
// This is not a parser - just simple implementation, which ignores optional segments, constraints, conditions,
// nesting of optional segments etc...
// Feel free to implement rich parser in JS ;)
var RailsRouter = {
expose_all : function(arr) {
for each (var route in arr) {
this.expose_route(route)
}
},
expose_route : function(route) {
this[ route.name + '_path' ] = function(attrs) {
attrs = attrs || {} //don't fail, if route has no options
var res;
//remove optional segments
res = route.path.replace( /([(][^():]*:\w+[^():]*[)])/g , '')
for each (var key in route.segment_keys) {
regexp = new RegExp('(:'+ key +')', 'g')
res = res.replace(regexp, attrs[key])
}
return res
}
},
};
# invoke this helper in layout
def expose_routes
json_routes = Rails.application.routes.routes.map {|r| {:name => r.name, :path => r.path, :segment_keys => r.segment_keys}}.to_json
javascript_tag "RailsRouter.expose_all(#{json_routes})"
end
RailsRouter.page_path({'id':1});
// "/pages/1"
// if pages resource is defined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment