convert all caps properly to snake format.

This commit is contained in:
Phil Wiebe 2014-07-01 17:12:10 -04:00
parent 6c5b95e2b2
commit a69602fe1c
2 changed files with 47 additions and 8 deletions

View File

@ -37,20 +37,31 @@ func newSafeMap() *safeMap {
var smap = newSafeMap()
var umap = newSafeMap()
func toSnake(u string) string {
if v := smap.Get(u); v != "" {
return v
}
func toSnakeBody(u string) string {
buf := bytes.NewBufferString("")
caps := 0
length := len(u)
for i, v := range u {
if i > 0 && v >= 'A' && v <= 'Z' {
buf.WriteRune('_')
if i > 0 && v >= 'A' && v <= 'Z' {
caps++
if caps == 1 || (i < length-1 && !(u[i+1] >= 'A' && u[i+1] <= 'Z')) {
buf.WriteRune('_')
}
} else {
caps = 0
}
buf.WriteRune(v)
}
s := strings.ToLower(buf.String())
return strings.ToLower(buf.String())
}
func toSnake(u string) string {
if v := smap.Get(u); v != "" {
return v
}
s := toSnakeBody(u)
go smap.Set(u, s)
return s
}

28
utils_test.go Normal file
View File

@ -0,0 +1,28 @@
package gorm
import "testing"
func TestToSnakeWithCapWord(t *testing.T) {
in, out := "BlockIOCount", "block_io_count"
if s := toSnake(in); s != out {
t.Errorf("toSnake(%v) = %v, want %v", in, s, out )
}
}
func TestToSnakeWithCapWordAtEnd(t *testing.T) {
in, out := "BlockIO", "block_io"
if s := toSnake(in); s != out {
t.Errorf("toSnake(%v) = %v, want %v", in, s, out )
}
}
func BenchmarkToSnake(b *testing.B) {
in := "BlockIOCount"
for i := 0; i < b.N; i++ {
toSnakeBody(in)
}
}