Last Updated: February 25, 2016
·
984
· antage

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 %>
}