Skip to content

Instantly share code, notes, and snippets.

@thebyrd
Last active December 25, 2015 05:19
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebyrd/6924190 to your computer and use it in GitHub Desktop.
Save thebyrd/6924190 to your computer and use it in GitHub Desktop.
A method that will inject npm modules listed as parameters in a constructor.
function SomeConstructor (request, npm, monk) {
// do something with the injected node modules
}
var instance = require('./injector')(SomeConstructor) // create a new instance with dependencies injected
module.exports = function (C) {
var params = C.toString()
.replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s))/mg,'')
.match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1]
.split(/,/)
for (var i = 0, param; param = params[i]; i++)
C = C.bind(this, require(param))
return new C()
}
@jdan
Copy link

jdan commented Oct 10, 2013

This is fire. My only concern is that "magic parameters" shepherd scare the shit out of me.

Super cool though. "I don't know regular expressions."

@thebyrd
Copy link
Author

thebyrd commented Oct 10, 2013

@jdan I don't ... ripped that shit from stack overflow.

@thebyrd
Copy link
Author

thebyrd commented Oct 10, 2013

@jdan @ox -> Still need to figure out what to do about npm modules with a dash in the middle like "aws-sdk"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment