Export all named routes from Ruby on Rails to Javascript (Rails 4 only)
app/assets/javascripts/routes.js.erb:
<%# export all named routes in javascript %>
Routes = {
<% routes = Rails.application.routes.routes.named_routes %>
<% routes.each_value do |route| %>
<%= "#{route.name}_path".to_json %>: function(<%= [route.required_parts + [""]].join(", ") %>format) {
var base = <%= route.format(Hash[route.required_parts.map { |p| [p, "__#{p}__"] }].merge(format: "__format__")).to_json %>;
<% route.required_parts.each do |param| %>
base = base.replace(<%= "__#{param}__".to_json %>, <%= param.to_s %>);
<% end %>
if (format != null) {
base = base.replace("__format__", format);
} else {
base = base.replace(".__format__", "");
}
return base;
},
<% end %>
}
Written by Anton Ageev
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Filed Under
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#