Created
May 3, 2011 12:55
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
}, | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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