Skip to content

Instantly share code, notes, and snippets.

@stevekinney
Last active February 27, 2020 08:11
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevekinney/570e526efce122657c31 to your computer and use it in GitHub Desktop.
Save stevekinney/570e526efce122657c31 to your computer and use it in GitHub Desktop.
Ruby's `method_missing` implemented in JavaScript using ES6 proxies.
// This will only work in environments that support ES6 Proxies.
// As of right now, that's pretty much only Firefox.
function Refrigerator(foods) {
this.foods = foods;
return new Proxy(this, {
get: function (receiver, name) {
if (name in receiver) {
return receiver[name];
} else if (name.match(/^findBy(.+)$/)) {
return receiver.find.bind(receiver, name.match(/^findBy(.+)$/)[1].toLowerCase());
}
}
});
}
Refrigerator.prototype.find = function (attribute, query) {
return this.foods.filter(function (food) {
return food[attribute] === query;
});
};
var cucumber = { name: "cucumber", type: "veggie", tastiness: 5 };
var bacon = { name: "bacon", type: "meat", tastiness: 10 };
var celery = { name: "celery", type: "veggie", tastiness: 3 };
var fridge = new Refrigerator([cucumber, bacon, celery]);
console.assert(fridge.foods.length === 3, 'FAILED: Properties should pass through');
console.assert(!fridge.garbage, 'FAILED: Garbage properties should return undefined');
console.assert(fridge.find('name', 'cucumber')[0].name === 'cucumber', 'FAILED: Regular finder');
console.assert(fridge.findByName('cucumber')[0].name === 'cucumber', 'FAILED: Proxy finder');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment