Skip to content

Commit

Permalink
allow useCurrent to ignore the fact that there is no context
Browse files Browse the repository at this point in the history
  • Loading branch information
iamnoah committed May 3, 2012
1 parent 128ccad commit f42785d
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 7 deletions.
6 changes: 3 additions & 3 deletions inject-core.coffee
Expand Up @@ -146,11 +146,11 @@ useInjector = (injector,fn) ->
finally
CONTEXT.pop()

inject.useCurrent = (fn) ->
inject.useCurrent = (fn,ignoreNoContext) ->
context = last(CONTEXT);
unless context
unless context or ignoreNoContext
noContext()
useInjector(context,fn)
if context then useInjector(context,fn) else fn

noContext = ->
throw new Error("""There is no current injector.
Expand Down
10 changes: 7 additions & 3 deletions inject-core.js
Expand Up @@ -169,11 +169,15 @@
};
};

inject.useCurrent = function(fn) {
inject.useCurrent = function(fn, ignoreNoContext) {
var context;
context = last(CONTEXT);
if (!context) noContext();
return useInjector(context, fn);
if (!(context || ignoreNoContext)) noContext();
if (context) {
return useInjector(context, fn);
} else {
return fn;
}
};

noContext = function() {
Expand Down
5 changes: 5 additions & 0 deletions test/qunit/inject_test.coffee
Expand Up @@ -355,6 +355,7 @@ test "destroy the context", ->


test "capturing the current context", ->
expect 2
injector = Inject
name: 'foo'
factory: -> 123
Expand All @@ -367,6 +368,10 @@ test "capturing the current context", ->
)),200)
)()

Inject.useCurrent(->
ok(true,'Can ignore no context')
,true).call this

test "error on no context", ->
expect(1)
try
Expand Down
6 changes: 5 additions & 1 deletion test/qunit/inject_test.js
Expand Up @@ -431,19 +431,23 @@

test("capturing the current context", function() {
var injector;
expect(2);
injector = Inject({
name: 'foo',
factory: function() {
return 123;
}
});
stop();
return injector(function() {
injector(function() {
return setTimeout(Inject.useCurrent(Inject.require('foo', function(foo) {
equals(foo, 123);
return start();
})), 200);
})();
return Inject.useCurrent(function() {
return ok(true, 'Can ignore no context');
}, true).call(this);
});

test("error on no context", function() {
Expand Down

0 comments on commit f42785d

Please sign in to comment.