Skip to content

Commit

Permalink
Add the Set method to the builder (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
sarulabs authored Jan 25, 2020
1 parent 60087ca commit 56f2d66
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ builder.Add(di.Def{
})
```

If you have an already built object to put in the container, you can use the `Set` shortcut:

```go
obj := &MyObject{}

builder, _ := di.NewBuilder()
builder.Set("my-object", obj)
```


## Object retrieval

Expand Down
10 changes: 10 additions & 0 deletions builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,16 @@ func (b *Builder) add(def Def) error {
return nil
}

// Set is a shortcut to add a definition for an already built object.
func (b *Builder) Set(name string, obj interface{}) error {
return b.add(Def{
Name: name,
Build: func(ctn Container) (interface{}, error) {
return obj, nil
},
})
}

// Build creates a Container in the most generic scope
// with all the definitions registered in the Builder.
func (b *Builder) Build() Container {
Expand Down
15 changes: 15 additions & 0 deletions builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,21 @@ func TestAddErrors(t *testing.T) {
require.Nil(t, err)
}

func TestSet(t *testing.T) {
b, _ := NewBuilder()

var err error

err = b.Set("", "error")
require.NotNil(t, err, "should not be able to set an object without a name")

err = b.Set("key", "value")
require.Nil(t, err)

ctn := b.Build()
require.Equal(t, "value", ctn.Get("key").(string))
}

func TestBuild(t *testing.T) {
ctn := (&Builder{}).Build()
require.Nil(t, ctn, "should have at least one scope to use Build")
Expand Down

0 comments on commit 56f2d66

Please sign in to comment.