Created
February 20, 2013 12:29
-
-
Save vslinko/4995192 to your computer and use it in GitHub Desktop.
small di written on coffeescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DI | |
constructor: -> | |
@container = di: @ | |
register: (name, value) -> | |
@container[name] = value | |
fetch: (name) -> | |
value = @container[name] | |
if typeof value is "function" | |
value = @inject value | |
value | |
inject: (injectable) -> | |
params = @params injectable | |
class Injector extends injectable | |
constructor: (args...) -> | |
for param, i in params | |
if typeof param is "undefined" | |
params[i] = args.shift() | |
injectable.apply @, params | |
Injector | |
params: (injectable) -> | |
compiledInjectable = injectable.toString() | |
matches = /^function \w*\(([^)]*)\)/.exec compiledInjectable | |
params = matches[1].split ", " | |
for name, i in params | |
params[i] = @fetch name | |
params | |
createInstance = -> | |
new DI | |
module.exports = createInstance | |
module.exports.DI = DI |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
assert = require "assert" | |
di = require "./di" | |
describe "DI", -> | |
di = null | |
beforeEach -> | |
di = di() | |
it "should contain 'di'", -> | |
assert.equal di, di.fetch "di" | |
it "should inject right dependencies", (callback) -> | |
di.register "a", "a" | |
di.register "b", (a) -> | |
assert.equal "a", a | |
callback() | |
di.register "c", (a, b) -> | |
assert.equal "a", a | |
b() | |
c = di.fetch "c" | |
c() | |
it "should replace undefined dependencies by arguments", (callback) -> | |
di.register "b", "b" | |
di.register "c", (a, b) -> | |
assert.equal "a", a | |
assert.equal "b", b | |
callback() | |
c = di.fetch "c" | |
c "a" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment