all files / src/ Rules.js

100% Statements 22/22
100% Branches 2/2
100% Functions 4/4
100% Lines 22/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                                  268× 268× 268× 268×   268×                                                     269×          
'use strict';
 
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
 
class Rules {
 
  /**
   * Constructor
   */
  constructor() {
    this.rules = {};
  }
 
  /**
   * Loads rules
   * @return {Object} Set of rules
   */
  load() {
    const rulesDirectory = path.join(__dirname, 'rules');
 
    try {
      fs.readdirSync(rulesDirectory).forEach((file) => {
        const beginIndex = 0;
        const endIndex = -3;
        const ruleId = file.slice(beginIndex, endIndex);
        const ruleModule = path.join(rulesDirectory, file);
 
        this._registerRule(ruleId, ruleModule);
      });
 
      return this.rules;
    } catch (err) {
      console.log(`Error - ${err}`);
 
      return false;
    }
  }
 
  /**
   * Loads a rule
   * @param  {String} ruleId Name of the rule
   * @return {Object}        Rule
   */
  get(ruleId) {
    const rule = this.rules[ruleId];
 
    if (typeof rule === 'undefined') {
      const errorMsg = `Rule, ${ruleId}, is invalid. Please ensure it matches a valid option.`;
 
      throw new Error(chalk.bold.red(errorMsg));
    }
 
    return require(this.rules[ruleId]);
  }
 
  /**
   * Registers a rule in the rules object
   * @param  {String}     ruleId      Name of the rule
   * @param  {String}     ruleModule  Path to rule
   * @return {undefined}              No return
   */
  _registerRule(ruleId, ruleModule) {
    this.rules[ruleId] = ruleModule;
  }
 
}
 
module.exports = Rules;