diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 68804c1..fb6f34a 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -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 diff --git a/content/content.go b/content/content.go index 4c92eb6..e703310 100644 --- a/content/content.go +++ b/content/content.go @@ -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, } } diff --git a/content/default.go b/content/default.go new file mode 100644 index 0000000..a529bcf --- /dev/null +++ b/content/default.go @@ -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 +} diff --git a/content/default_test.go b/content/default_test.go new file mode 100644 index 0000000..6aef88a --- /dev/null +++ b/content/default_test.go @@ -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) + }) +}