Helper for a standardized form of Policy Object inspired by the Code Climate Blog. Designed to be used in the Node environment.
var ActiveUserPolicy = BasePolicy.extend({
allowed: function(user) {
return user.emailConfirmed? &&
user.lastLoggedInAt > moment().subtract(14, 'days');
}
});
function emailAllowedUsers(users, policy) {
users.forEach(function(user) {
if (policy.allowed(user)) {
sendEmail(user);
}
});
};
emailAllowedUsers(users, ActiveUserPolicy.create());
It can also work at the 'class' level:
var ActiveUserPolicy = BasePolicy.extend({
allowed: function(user) {
return user.emailConfirmed? &&
user.lastLoggedInAt > moment().subtract(14, 'days');
}
});
ActiveUserPolicy.allowed(user) // => true or false
It also accepts arguments in the constructor:
var ActiveUserPolicy = BasePolicy.extend({
init: function(daysAgo) {
this.daysAgo = daysAgo;
},
allowed: function(user) {
return user.emailConfirmed? &&
user.lastLoggedInAt > moment().subtract(this.daysAgo, 'days');
}
});