Skip to content

Commit

Permalink
Merge pull request #17 from gobuffalo/feature-adding-default-helper
Browse files Browse the repository at this point in the history
Adding default helper
  • Loading branch information
paganotoni authored Apr 24, 2021
2 parents 6fa02f7 + 0f8fb80 commit 2f3bb74
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 5 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
go-version: [1.12.x, 1.13.x]
go-version: [1.15.x, 1.16.x]
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout Code
Expand Down
10 changes: 6 additions & 4 deletions content/content.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ import "github.com/gobuffalo/helpers/hctx"

// Keys to be used in templates for the functions in this package.
const (
OfKey = "contentOf"
ForKey = "contentFor"
OfKey = "contentOf"
ForKey = "contentFor"
DefaultKey = "default"
)

// New returns a map of the helpers within this package.
func New() hctx.Map {
return hctx.Map{
OfKey: ContentOf,
ForKey: ContentFor,
OfKey: ContentOf,
ForKey: ContentFor,
DefaultKey: WithDefault,
}
}
14 changes: 14 additions & 0 deletions content/default.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package content

import "github.com/gobuffalo/helpers/hctx"

// WithDefault returns the key if exists, otherwise it returns
// defaultValue passed.
func WithDefault(key string, defaultValue interface{}, help hctx.HelperContext) interface{} {
value := help.Value(key)
if value != nil {
return value
}

return defaultValue
}
43 changes: 43 additions & 0 deletions content/default_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package content

import (
"testing"

"github.com/gobuffalo/helpers/helptest"
"github.com/stretchr/testify/require"
)

func Test_Default(t *testing.T) {
r := require.New(t)
def := "notavailable"

t.Run("NotPresent", func(t *testing.T) {
hc := helptest.NewContext()
res := WithDefault("nothere", def, hc)
r.Equal(res, def)
})

t.Run("Present", func(t *testing.T) {
hc := helptest.NewContext()
hc.Set("there", "someval")
res := WithDefault("there", def, hc)
r.Equal(res, "someval")
})

t.Run("PresentNil", func(t *testing.T) {
hc := helptest.NewContext()
hc.Set("nil", nil)
res := WithDefault("nil", def, hc)
r.Equal(res, "notavailable")
})

t.Run("PresentPointer", func(t *testing.T) {
hc := helptest.NewContext()
a := "something"
p := &a
hc.Set("pointer", p)
res := WithDefault("pointer", def, hc)
r.Equal(res, p)
r.NotEqual(res, a)
})
}

0 comments on commit 2f3bb74

Please sign in to comment.