Skip to content

Instantly share code, notes, and snippets.

@cpojer
Created March 29, 2011 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpojer/892920 to your computer and use it in GitHub Desktop.
Save cpojer/892920 to your computer and use it in GitHub Desktop.
(function(){
this.Accessor = function(singular, plural){
singular = (singular || '').capitalize();
if (!plural) plural = singular + 's';
var accessor = {}, matchers = [];
this['define' + singular] = function(key, value){
if (typeOf(key) == 'regexp') matchers.push({regexp: key, action: value});
else accessor[key] = value;
return this;
};
this['define' + plural] = function(object){
for (var key in object) accessor[key] = object[key];
return this;
};
this['match' + singular] = function(name){
for (var l = matchers.length; l--; l){
var matcher = matchers[l], match = name.match(matcher.regexp);
if (match && (match = match.slice(1))) return function(){
return matcher.action.apply(this, Array.slice(arguments).append(match));
};
}
return null;
};
this['lookup' + singular] = function(key){
return accessor[key] || null;
};
this['lookup' + plural] = function(keys){
return Object.subset(accessor, keys);
};
return this;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment