Skip to content

Commit

Permalink
Extract method FieldByName
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Jul 15, 2014
1 parent 96db2a1 commit 3eb4ada
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 16 deletions.
2 changes: 1 addition & 1 deletion callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func sortProcessors(cps []*callback_processor) []*func(scope *Scope) {
} else if cp.remove {
fmt.Printf("[info] removing callback `%v` from %v\n", cp.name, fileWithLineNum())
} else {
fmt.Println("[warning] duplicated callback `%v` from %v\n", cp.name, fileWithLineNum())
fmt.Printf("[warning] duplicated callback `%v` from %v\n", cp.name, fileWithLineNum())
}
}
names = append(names, cp.name)
Expand Down
16 changes: 1 addition & 15 deletions scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,21 +111,7 @@ func (scope *Scope) HasColumn(name string) bool {

// FieldByName to get column's value and existence
func (scope *Scope) FieldByName(name string) (interface{}, bool) {
data := reflect.Indirect(reflect.ValueOf(scope.Value))

if data.Kind() == reflect.Struct {
if field := data.FieldByName(name); field.IsValid() {
return field.Interface(), true
}
} else if data.Kind() == reflect.Slice {
elem := data.Type().Elem()
if elem.Kind() == reflect.Ptr {
return nil, reflect.New(data.Type().Elem().Elem()).Elem().FieldByName(name).IsValid()
} else {
return nil, reflect.New(data.Type().Elem()).Elem().FieldByName(name).IsValid()
}
}
return nil, false
return FieldByName(name, scope.Value)
}

// SetColumn to set the column's value
Expand Down
23 changes: 23 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,29 @@ func (s *safeMap) Get(key string) string {
return s.m[key]
}

func FieldByName(name string, value interface{}, withAddr ...bool) (interface{}, bool) {
data := reflect.Indirect(reflect.ValueOf(value))
name = snakeToUpperCamel(name)

if data.Kind() == reflect.Struct {
if field := data.FieldByName(name); field.IsValid() {
if len(withAddr) > 0 && field.CanAddr() {
return field.Addr().Interface(), true
} else {
return field.Interface(), true
}
}
} else if data.Kind() == reflect.Slice {
elem := data.Type().Elem()
if elem.Kind() == reflect.Ptr {
return nil, reflect.New(data.Type().Elem().Elem()).Elem().FieldByName(name).IsValid()
} else {
return nil, reflect.New(data.Type().Elem()).Elem().FieldByName(name).IsValid()
}
}
return nil, false
}

func newSafeMap() *safeMap {
return &safeMap{l: new(sync.RWMutex), m: make(map[string]string)}
}
Expand Down

0 comments on commit 3eb4ada

Please sign in to comment.