Skip to content

Instantly share code, notes, and snippets.

@armstrjare
Created March 26, 2012 03:18
Show Gist options
  • Save armstrjare/2202614 to your computer and use it in GitHub Desktop.
Save armstrjare/2202614 to your computer and use it in GitHub Desktop.
# 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