-
In top of a prior app/assets/javascripts/XXX.js.erb (replace XXX by the name of your choice) file, add:
<% environment.context_class.instance_eval { include Rails.application.routes.url_helpers } %>
-
Copy the result of the command
cat app/assets/javascripts/routes.coffee | coffee -scb
into the same app/assets/javascripts/XXX.js.erb file. -
Expose the willed routes to Javascript:
<% Rails.application.routes.named_routes.routes.each_value do |r| %>
<% next if r.name =~ /(?:^|[^[[:alpha:]]])admin(?:[^[[:alpha:]]]|$)/ %> # skip any routes containing "admin"
new Route('<%= r.name %>', '<%= r.path.spec.to_s %>', /<%= r.path.to_regexp.to_s.sub(/\\A/, '^').sub(/\\Z/, '$').gsub(/\(\?-mix:/, '(?:') %>/, <%= r.segments.to_json %>, <%= r.required_parts.to_json %>, <%= r.optional_parts.to_json %>);
<% end %>
For lazy one, just grab the content of 0.js.erb
Then, in your javascripts assets files, you should be able to use:
Route.match(name)
: test if current URL match the given named rails route (without any _path/_url suffix) and, if so, extract its parametersRoute.path(name [, args])
: build path to the given named rails route. Optional args is a hash (object) of parameters (name => value)
Examples with routes from Getting Started with Rails:
if (false !== (params = Route.match('edit_article')) {
console.log('You are editing article #' + params.id);
} else {
// you are on an another location
}
$.get(
Route.path('article', { id: 3, format: 'html' }), # => /articles/3.html
function (data) {
# do somehting with the result
}
);
Example with hashing them in md5:
For convenience, monkey patch String class:
require 'digest/md5'
class String
def md5
Digest::MD5.hexdigest self
end
end
-
Replace
new Route('<%= r.name %>'
withnew Route('<%= r.name.md5 %>'
-
Change extension of your asset file from .js to .erb.js if it is not already the case
-
Instead of
'name'
as first argument of Route.path and Route.match, use'<%= 'name'.md5 %>'
Because there is no equivalent to Route.match
.