Skip to content

Instantly share code, notes, and snippets.

@tal
Created May 8, 2012 22:37
Show Gist options
  • Select an option

  • Save tal/2640029 to your computer and use it in GitHub Desktop.

Select an option

Save tal/2640029 to your computer and use it in GitHub Desktop.
/**
* Path Set
* A libary for storing and generating paths for an application based on params
* @author Tal Atlas <[email protected]>
*
* ps = new PathSet({
* root: '/',
* album: '/albums/:id(.:format)',
* album_pictures: '/albums/:album_id/pictures(/:id)(.:format)'
* });
*
* ps.album_pictures_path({album_id: 123}) // => /albums/123/pictures
* ps.album_pictures_path({album_id: 123, foo: 'bar'}) // => /albums/123/pictures?foo=bar
* ps.album_pictures_path({album_id: 123, format: 'json'}) // => /albums/123/pictures.json
* ps.album_pictures_path({album_id: 123, id: 345}) // => /albums/123/pictures/345
*/
(function() {
window.PathSet = function PathSet(paths,opts) {
var url, self = this, pathName;
this.paths = paths;
opts || (opts = {});
this.defaults = opts.defaults || {};
function buildFunc(pathName) {
self[pathName+'_path'] = function(params) {
var defaults = self.defaults[pathName], param;
if (defaults) {
for (param in defaults) {
if (params[param] === undefined && defaults[param] !== undefined) {
params[param] = defaults[param];
}
}
}
return PathSet.matchPath(paths[pathName],params);
}
}
for (pathName in paths) {
buildFunc(pathName);
}
};
var PATH_REG = /(.+)(?:\((?:[^:)]*:\w[a-z0-9:\/-_(.]*)\))/i, r20 = /%20/g;
PathSet.matchPath = function matchPath(path,params,domain) {
var re = /:(\w+)/g, match, pathMatch, value, url;
url = path;
params || (params = {});
// Match all values in url and replace them with values from the form
while (match = re.exec(path)) {
value = params[match[1]];
if (value) {
url = url.replace(match[0],value);
delete params[match[1]];
}
}
// Remove optional portions of the path
while (match = url.match(PATH_REG)) {
url = url.replace(PATH_REG,'$1');
}
url = url.replace(/[()]/g,'');
// Append all additional params to the query string
var additional_params = []
if (jQuery && jQuery.param) {
additional_params.push(jQuery.param(params));
} else {
for (var param in params) {
additional_params.push((encodeURIComponent(param)+'='+encodeURIComponent(params[param])).replace(r20,'+'));
}
}
if (additional_params.length) {
if (url.match(/\?/)) url = url + '&';
else url = url+'?';
url = url + additional_params.join('&');
}
if (domain) {
url = domain + url;
}
return url;
};
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment