Skip to content

Instantly share code, notes, and snippets.

@bradhe
Created March 10, 2012 05:07
Show Gist options
  • Save bradhe/2010242 to your computer and use it in GitHub Desktop.
Save bradhe/2010242 to your computer and use it in GitHub Desktop.
Generates a set of JavaScript functions that behave very similarly to Rails' named routes. Even plays nice with the assets pipeline.
module Sprockets::Helpers::RailsHelper
require File.join(Rails.root, "app", "helpers", "assets_helper.rb")
include AssetsHelper
end
module AssetsHelper
def route_names_with_paths
# White list of all of the routes.
allowed_controllers = %w{controllers you want to generate routes for}
selected_routes = Rails.application.routes.routes.select do |route|
controller = route.requirements[:controller]
allowed_controllers.include?(controller)
end
# All we really care about is the name and the path.
selected_routes.inject({}) do |h, r|
# For whatever reason, it has this special format thinger on the end.
h[r.name] = r.path.gsub(%r{\(\.:format\)$}, '').strip
h
end.to_json.html_safe
end
end
(function(w) {
function evaluateRouteWithPath(path, params, options) {
options = options || {}
var complete = path;
for(var i in params) {
var param = params[i];
if(typeof(param) === 'object') {
param = param.toParam();
}
else if(typeof(param) == 'function') {
param = param();
}
complete = complete.replace(/(\:\w+)/, param);
}
if(options.format) {
complete += '.json';
}
return complete;
}
var relativeRoute = function(path) {
return function() {
var args = Array.prototype.slice.call(arguments);
// Check options.
var options = args.pop();
if(typeof(options) !== 'object') {
args.push(options);
options = null;
}
return evaluateRouteWithPath(path, arguments);
};
};
var absoluteRoute = function(path) {
var host = document.location.protocol + '//<%= API_DOMAIN %>' + path;
return function() {
var args = Array.prototype.slice.call(arguments);
// Check options.
var options = args.pop();
if(typeof(options) !== 'object') {
args.push(options);
options = null;
}
return evaluateRouteWithPath(host, args, options);
}
};
var routes = <%= route_names_with_paths %>;
for(var i in routes) {
if(typeof(routes[i]) !== 'string') {
continue;
}
window[i + '_path'] = relativeRoute(routes[i]);
window[i + '_url'] = absoluteRoute(routes[i]);
}
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment