✨ Add time-based generators
This commit is contained in:
parent
0fc4369679
commit
ee627547a8
3 changed files with 45 additions and 2 deletions
|
|
@ -1,9 +1,13 @@
|
|||
package nomino
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type generator func() (string, error)
|
||||
|
||||
func setGenerator(c *config, g generator) {
|
||||
c.generator = g
|
||||
}
|
||||
|
|
@ -21,3 +25,25 @@ func WithUUID() Option {
|
|||
setGenerator(c, uuidGen)
|
||||
}
|
||||
}
|
||||
|
||||
const FileTimestamp string = "2006-01-02_03-05-06-0700"
|
||||
|
||||
func WithTimestamp() Option {
|
||||
return WithTimestampFormat(FileTimestamp)
|
||||
}
|
||||
|
||||
func WithTimestampFormat(f string) Option {
|
||||
return WithFormattedTime(time.Now(), f)
|
||||
}
|
||||
|
||||
func WithTime(t time.Time) Option {
|
||||
return WithFormattedTime(t, FileTimestamp)
|
||||
}
|
||||
|
||||
func WithFormattedTime(t time.Time, f string) Option {
|
||||
return func(c *config) {
|
||||
setGenerator(c, func() (string, error) {
|
||||
return t.Format(f), nil
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package nomino
|
|||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
|
@ -31,3 +32,21 @@ func TestWithUUIDFail(t *testing.T) {
|
|||
_, err := c.generator()
|
||||
assert.Equal(t, errors.New("sorry"), err)
|
||||
}
|
||||
|
||||
func TestWithTimestamp(t *testing.T) {
|
||||
var c config
|
||||
WithTimestamp()(&c)
|
||||
n := time.Now()
|
||||
st, err := c.generator()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, n.Format(FileTimestamp), st)
|
||||
}
|
||||
|
||||
func TestWithTime(t *testing.T) {
|
||||
var c config
|
||||
d := time.Date(1986, time.March, 28, 12, 0, 0, 0, time.UTC)
|
||||
WithTime(d)(&c)
|
||||
st, err := c.generator()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, d.Format(FileTimestamp), st)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,8 +2,6 @@ package nomino
|
|||
|
||||
import "strings"
|
||||
|
||||
type generator func() (string, error)
|
||||
|
||||
type config struct {
|
||||
original string
|
||||
prefix string
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue