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