Implement method interface to table name

This commit is contained in:
Jinzhu 2013-10-26 14:40:37 +08:00
parent 9ef4a2669c
commit e935b4772b
2 changed files with 20 additions and 17 deletions

2
orm.go
View File

@ -26,7 +26,7 @@ type Orm struct {
}
func (s *Orm) setModel(model interface{}) (err error) {
s.TableName = "users"
s.TableName = interfaceToTableName(model)
s.PrimaryKey = "id"
return
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"reflect"
"regexp"
"strings"
)
@ -35,6 +36,7 @@ func quoteMap(values []string) (results []string) {
}
return
}
func toSnake(s string) string {
buf := bytes.NewBufferString("")
for i, v := range s {
@ -46,22 +48,6 @@ func toSnake(s string) string {
return strings.ToLower(buf.String())
}
func interfaceToSnake(f interface{}) string {
t := reflect.TypeOf(f)
for {
c := false
switch t.Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice:
t = t.Elem()
c = true
}
if !c {
break
}
}
return toSnake(t.Name())
}
func snakeToUpperCamel(s string) string {
buf := bytes.NewBufferString("")
for _, v := range strings.Split(s, "_") {
@ -73,6 +59,23 @@ func snakeToUpperCamel(s string) string {
return buf.String()
}
func interfaceToTableName(f interface{}) string {
t := reflect.TypeOf(f)
for {
c := false
switch t.Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice:
t = t.Elem()
c = true
}
if !c {
break
}
}
reg, _ := regexp.Compile("s*$")
return reg.ReplaceAllString(toSnake(t.Name()), "s")
}
func debug(value interface{}) {
fmt.Printf("***************\n")
fmt.Printf("%+v\n\n", value)