From 9602526726d0fe88b27e5343f397bce6b4c53968 Mon Sep 17 00:00:00 2001 From: Paul Gier Date: Thu, 21 Nov 2019 11:32:53 -0600 Subject: [PATCH] better handling of multi-word idents Replace only the last part of an ident when pluralizing --- ident.go | 13 +++++++++++++ name/tablize_test.go | 1 + pluralize.go | 6 +++--- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/ident.go b/ident.go index 78b51d4..06c1b77 100644 --- a/ident.go +++ b/ident.go @@ -94,6 +94,19 @@ func toParts(s string) []string { var _ encoding.TextUnmarshaler = &Ident{} var _ encoding.TextMarshaler = &Ident{} +// LastPart returns the last part/word of the original string +func (i *Ident) LastPart() string { + if len(i.Parts) == 0 { + return "" + } + return i.Parts[len(i.Parts)-1] +} + +// ReplaceSuffix creates a new Ident with the original suffix replaced by new +func (i Ident) ReplaceSuffix(orig string, new string) Ident { + return New(strings.TrimSuffix(i.Original, orig) + new) +} + //UnmarshalText unmarshalls byte array into the Ident func (i *Ident) UnmarshalText(data []byte) error { (*i) = New(string(data)) diff --git a/name/tablize_test.go b/name/tablize_test.go index ea4b7d1..e0c5e5f 100644 --- a/name/tablize_test.go +++ b/name/tablize_test.go @@ -24,6 +24,7 @@ func Test_Tableize(t *testing.T) { {"People", "people"}, {"people", "people"}, {"BigPerson", "big_people"}, + {"Wild Ox", "wild_oxen"}, } for _, tt := range table { diff --git a/pluralize.go b/pluralize.go index 1b9d43e..ded6b59 100644 --- a/pluralize.go +++ b/pluralize.go @@ -20,7 +20,7 @@ func Pluralize(s string) string { // person = people // datum = data func (i Ident) Pluralize() Ident { - s := i.Original + s := i.LastPart() if len(s) == 0 { return New("") } @@ -33,11 +33,11 @@ func (i Ident) Pluralize() Ident { return i } if p, ok := singleToPlural[ls]; ok { - return New(p) + return i.ReplaceSuffix(s, p) } for _, r := range pluralRules { if strings.HasSuffix(ls, r.suffix) { - return New(r.fn(s)) + return i.ReplaceSuffix(s, r.fn(s)) } }