Skip to content

Instantly share code, notes, and snippets.

@rttomlinson
Last active April 19, 2017 03:24
Show Gist options
  • Select an option

  • Save rttomlinson/ab8a032c80ab47f284a88ffc10e78052 to your computer and use it in GitHub Desktop.

Select an option

Save rttomlinson/ab8a032c80ab47f284a88ffc10e78052 to your computer and use it in GitHub Desktop.
Helps dynamically add dependencies to a single exporting object
// helpers/index.js
var fs = require('fs');
var path = require('path');
var express = require('express');
var basename = path.basename(__filename);
var Helpers = {};
// Object to hold registered helpers
Helpers.registered = {};
// Register a single helper or
// a module
Helpers.register = function(key, fn) {
if (typeof key === 'object') {
// Iterate through keys
var helpers = key;
for (var key in helpers) {
// Register helper function
var fn = helpers[key];
this.registered[key] = fn;
}
} else {
// Register a single helper
// function
this.registered[key] = fn;
}
};
// Register all helper files
var files = fs.readdirSync(__dirname);
files.forEach((filename) => {
// If the file is not this file
if (filename !== basename) {
// Require it and register its
// helpers
var helperModule = require(`./${ filename }`);
Helpers.register(helperModule);
}
});
module.exports = Helpers;
var UsersHelper = {};
UsersHelper.usersPath = () => '/users/';
UsersHelper.userPath = (id) => `/users/${ id }`;
UsersHelper.newUserPath = () => '/users/new';
UsersHelper.editUserPath = (id) => `/users/${ id }/edit`;
UsersHelper.destroyUserPath = (id) => `/users/${ id }/?_method=delete`;
module.exports = UsersHelper;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment