inflect.go (2263B)
1 // Copyright 2017 The Hugo Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 // Package inflect provides template functions for the inflection of words. 15 package inflect 16 17 import ( 18 "strconv" 19 "strings" 20 21 _inflect "github.com/gobuffalo/flect" 22 "github.com/spf13/cast" 23 ) 24 25 // New returns a new instance of the inflect-namespaced template functions. 26 func New() *Namespace { 27 return &Namespace{} 28 } 29 30 // Namespace provides template functions for the "inflect" namespace. 31 type Namespace struct{} 32 33 // Humanize returns the humanized form of a single parameter. 34 // 35 // If the parameter is either an integer or a string containing an integer 36 // value, the behavior is to add the appropriate ordinal. 37 // 38 // Example: "my-first-post" -> "My first post" 39 // Example: "103" -> "103rd" 40 // Example: 52 -> "52nd" 41 func (ns *Namespace) Humanize(in any) (string, error) { 42 word, err := cast.ToStringE(in) 43 if err != nil { 44 return "", err 45 } 46 47 if word == "" { 48 return "", nil 49 } 50 51 _, ok := in.(int) // original param was literal int value 52 _, err = strconv.Atoi(word) // original param was string containing an int value 53 if ok || err == nil { 54 return _inflect.Ordinalize(word), nil 55 } 56 57 str := _inflect.Humanize(word) 58 return _inflect.Humanize(strings.ToLower(str)), nil 59 } 60 61 // Pluralize returns the plural form of a single word. 62 func (ns *Namespace) Pluralize(in any) (string, error) { 63 word, err := cast.ToStringE(in) 64 if err != nil { 65 return "", err 66 } 67 68 return _inflect.Pluralize(word), nil 69 } 70 71 // Singularize returns the singular form of a single word. 72 func (ns *Namespace) Singularize(in any) (string, error) { 73 word, err := cast.ToStringE(in) 74 if err != nil { 75 return "", err 76 } 77 78 return _inflect.Singularize(word), nil 79 }