Permalink
Browse files

resolve simple dependencies

  • Loading branch information...
1 parent 92400c8 commit cb7802f36cfb35171c33203371ae2398276d2215 @davidmfoley committed Apr 18, 2012
Showing with 35 additions and 1 deletion.
  1. +15 −0 lib/container.coffee
  2. +20 −1 test/container_spec.coffee
View
15 lib/container.coffee
@@ -0,0 +1,15 @@
+module.exports = class Container
+ constructor: ->
+ @typeMap = {}
+
+ register : (name, constructor, dependencies...) =>
+ @typeMap[name.toLowerCase()] =
+ ctor: constructor
+ dependencies : dependencies ? []
+
+ get : (name)->
+ info = @typeMap[name.toLowerCase()]
+ unless info.instance
+ deps = (@get(dep) for dep in info.dependencies)
+ info.instance = new info.ctor(deps...)
+ info.instance
View
21 test/container_spec.coffee
@@ -1,2 +1,21 @@
+Container = require '../lib/container'
describe 'Container', ->
- it 'should do something', ->
+ container = null
+
+ beforeEach ->
+ container = new Container
+
+ it 'can construct an object with no dependencies', ->
+ container.register('DeepThought', DeepThought)
+ container.get('DeepThought').answer.should.equal(42)
+
+ it 'can create an object with a dependency', ->
+ container.register('DeepThought', DeepThought)
+ container.register('Arthur', Arthur, 'DeepThought')
+ container.get('Arthur').deepThought.answer.should.equal(42)
+
+class DeepThought
+ answer: 42
+
+class Arthur
+ constructor : (@deepThought) ->

0 comments on commit cb7802f

Please sign in to comment.