github.com/segakazzz/buffalo@v0.16.22-0.20210119082501-1f52048d3feb/routenamer.go (about) 1 package buffalo 2 3 import ( 4 "strings" 5 6 "github.com/gobuffalo/flect" 7 "github.com/gobuffalo/flect/name" 8 ) 9 10 // RouteNamer is in charge of naming a route from the 11 // path assigned, this name typically will be used if no 12 // name is assined with .Name(...). 13 type RouteNamer interface { 14 // NameRoute receives the path and returns the name 15 // for the route. 16 NameRoute(string) string 17 } 18 19 // BaseRouteNamer is the default route namer used by apps. 20 type baseRouteNamer struct{} 21 22 func (drn baseRouteNamer) NameRoute(p string) string { 23 if p == "/" || p == "" { 24 return "root" 25 } 26 27 resultParts := []string{} 28 parts := strings.Split(p, "/") 29 30 for index, part := range parts { 31 32 originalPart := parts[index] 33 34 var previousPart string 35 if index > 0 { 36 previousPart = parts[index-1] 37 } 38 39 var nextPart string 40 if len(parts) > index+1 { 41 nextPart = parts[index+1] 42 } 43 44 isIdentifierPart := strings.Contains(part, "{") && (strings.Contains(part, flect.Singularize(previousPart))) 45 isSimplifiedID := part == `{id}` 46 47 if isIdentifierPart || isSimplifiedID || part == "" { 48 continue 49 } 50 51 if strings.Contains(nextPart, "{") { 52 part = flect.Singularize(part) 53 } 54 55 if originalPart == "new" || originalPart == "edit" { 56 resultParts = append([]string{part}, resultParts...) 57 continue 58 } 59 60 if strings.Contains(previousPart, "}") { 61 resultParts = append(resultParts, part) 62 continue 63 } 64 65 resultParts = append(resultParts, part) 66 } 67 68 if len(resultParts) == 0 { 69 return "unnamed" 70 } 71 72 underscore := strings.TrimSpace(strings.Join(resultParts, "_")) 73 return name.VarCase(underscore) 74 }