Skip to content

Instantly share code, notes, and snippets.

@thebyrd
Last active December 25, 2015 05:19
Show Gist options
  • Select an option

  • Save thebyrd/6924190 to your computer and use it in GitHub Desktop.

Select an option

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

jdan commented Oct 10, 2013

Copy link
Copy Markdown

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

thebyrd commented Oct 10, 2013

Copy link
Copy Markdown
Author

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

@thebyrd

thebyrd commented Oct 10, 2013

Copy link
Copy Markdown
Author

@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