Created
March 26, 2012 03:18
-
-
Save armstrjare/2202614 to your computer and use it in GitHub Desktop.
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
# Provides a method of accessing our URL routes from JavaScript. | |
<%# Helper function to define our routes %> | |
<% route = lambda { |*args| | |
route_name = args.shift | |
route_args = args.map { |kw| ":#{kw}" } # Provide interpolation of route arguments | |
route_args.push({ :only_path => true}) | |
url = MyApp::Application.routes.url_helpers.send("#{route_name}_url", *route_args).to_json | |
"#{route_name}_url : route(#{url})" } %> | |
# Route wrapper function. All routes are functions with return a route URL. | |
# That function takes a hash of arguments and options. | |
route = (url) -> | |
(parameters = {}) -> | |
# If not a hash, first argument is the ID. | |
if typeof paremeters == "string" or typeof parameters == "number" | |
parameters = { id : parameters } | |
# Parse out the parameters in the URL | |
processedUrl = url | |
$.each parameters, (key, value) -> | |
processedUrl = processedUrl.replace(":#{key}", escape(value)) | |
# Replace out any unused arguments | |
processedUrl = processedUrl.replace(/([0-9a-z_]+)=\:(\1)(&?)/g, "") | |
processedUrl | |
MyApp.routes = | |
<%= route[:posts] %> | |
<%= route[:post, :id] %> | |
<%= route[:post_comment, :post_id, :id] %> | |
<%= route[:root] %> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment