diff --git a/ident.go b/ident.go index 171abbc..f70f175 100644 --- a/ident.go +++ b/ident.go @@ -1,6 +1,7 @@ package flect import ( + "encoding" "regexp" "strings" "unicode" @@ -84,3 +85,15 @@ func toParts(s string) []string { return parts } + +var _ encoding.TextUnmarshaler = &Ident{} +var _ encoding.TextMarshaler = &Ident{} + +func (i *Ident) UnmarshalText(data []byte) error { + (*i) = New(string(data)) + return nil +} + +func (i Ident) MarshalText() ([]byte, error) { + return []byte(i.Original), nil +} diff --git a/ident_test.go b/ident_test.go index d1e4c77..f648248 100644 --- a/ident_test.go +++ b/ident_test.go @@ -50,3 +50,14 @@ func Test_New(t *testing.T) { }) } } +func Test_MarshalText(t *testing.T) { + r := require.New(t) + + n := New("mark") + b, err := n.MarshalText() + r.NoError(err) + r.Equal("mark", string(b)) + + r.NoError((&n).UnmarshalText([]byte("bates"))) + r.Equal("bates", n.String()) +} diff --git a/name/name.go b/name/name.go index fd14e0c..c90cfb2 100644 --- a/name/name.go +++ b/name/name.go @@ -1,6 +1,7 @@ package name import ( + "encoding" "strings" "github.com/gobuffalo/flect" @@ -47,3 +48,15 @@ func (i Ident) Group() Ident { parts = append(parts, last) return New(strings.Join(parts, "")) } + +var _ encoding.TextUnmarshaler = &Ident{} +var _ encoding.TextMarshaler = &Ident{} + +func (i *Ident) UnmarshalText(data []byte) error { + (*i) = New(string(data)) + return nil +} + +func (i Ident) MarshalText() ([]byte, error) { + return []byte(i.Original), nil +} diff --git a/name/name_test.go b/name/name_test.go index d29bf65..a0f201a 100644 --- a/name/name_test.go +++ b/name/name_test.go @@ -69,3 +69,15 @@ func Test_Group(t *testing.T) { }) } } + +func Test_MarshalText(t *testing.T) { + r := require.New(t) + + n := New("mark") + b, err := n.MarshalText() + r.NoError(err) + r.Equal("mark", string(b)) + + r.NoError((&n).UnmarshalText([]byte("bates"))) + r.Equal("bates", n.String()) +}