Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Returns an existing Scope with the same name #401

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,25 @@ func newScope() *Scope {
return s
}

// Scope creates a new Scope with the given name and options from current Scope.
// Scope creates a new Scope with the given name and options from current Scope,
// or returns an existing Scope with the same name.
// Any constructors that the current Scope knows about, as well as any modifications
// made to it in the future will be propagated to the child scope.
// However, no modifications made to the child scope being created will be propagated
// to the parent Scope.
func (s *Scope) Scope(name string, opts ...ScopeOption) *Scope {
// Check if a child scope with the same name already exists.
for _, s := range s.childScopes {
if s.name == name {
// in future, we may want to allow users to override options
for _, opt := range opts {
opt.noScopeOption()
}
return s
}
}

// otherwise, create a new child scope.
child := newScope()
child.name = name
child.parentScope = s
Expand Down
15 changes: 15 additions & 0 deletions scope_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,21 @@ func TestScopedOperations(t *testing.T) {

child.RequireInvoke(func(T2) {})
})

t.Run("return existing scope if it already exists", func(t *testing.T) {
type A struct{}
type B struct{}

c := digtest.New(t)
s := c.Scope("child")
s.RequireProvide(func() *A { return &A{} })
s.RequireProvide(func() *B { return &B{} })

// Reuse the existing child scope.
s2 := c.Scope("child")
s2.RequireInvoke(func(*A) {})
s2.RequireInvoke(func(*B) {})
})
}

func TestScopeFailures(t *testing.T) {
Expand Down