Skip to content

Instantly share code, notes, and snippets.

@thomasboyt
Created July 17, 2013 14:42
Show Gist options
  • Select an option

  • Save thomasboyt/6021224 to your computer and use it in GitHub Desktop.

Select an option

Save thomasboyt/6021224 to your computer and use it in GitHub Desktop.
weird rails-y findBy method in JS
var myClassCollection = [];
var _MyClass = function(id, foo) {
this.id = id;
this.foo = foo;
// some sort of arbitrary storage thing
this.collection[id] = this;
}
_MyClass.prototype.collection = myClassCollection;
var MyClass = new Proxy(_MyClass, {
get: function(target, name) {
var match = /^findBy_(.*)/.exec(name);
if (match) {
name = match[1];
return function(query) {
return this.prototype.collection.filter(function(item) {
return item[name] == query;
});
}.bind(target);
}
return target[name];
}
});
var instance = new MyClass(5, "bar");
console.log(MyClass.findBy_id(5));
console.log(MyClass.findBy_foo("bar"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment