Add GetSliceValues to help clean up eager loads
This commit is contained in:
parent
eae23ae42b
commit
7ce4146854
2 changed files with 49 additions and 1 deletions
|
@ -249,7 +249,7 @@ func GetStructValues(obj interface{}, columns ...string) []interface{} {
|
|||
for i, c := range columns {
|
||||
field := val.FieldByName(strmangle.TitleCase(c))
|
||||
if !field.IsValid() {
|
||||
panic(fmt.Sprintf("Unable to find field with name: %s\n%#v", strmangle.TitleCase(c), obj))
|
||||
panic(fmt.Sprintf("unable to find field with name: %s\n%#v", strmangle.TitleCase(c), obj))
|
||||
}
|
||||
ret[i] = field.Interface()
|
||||
}
|
||||
|
@ -257,6 +257,24 @@ func GetStructValues(obj interface{}, columns ...string) []interface{} {
|
|||
return ret
|
||||
}
|
||||
|
||||
// GetSliceValues returns the values (as interface) of the matching columns in obj.
|
||||
func GetSliceValues(slice []interface{}, columns ...string) []interface{} {
|
||||
ret := make([]interface{}, len(slice)*len(columns))
|
||||
|
||||
for i, obj := range slice {
|
||||
val := reflect.Indirect(reflect.ValueOf(obj))
|
||||
for j, c := range columns {
|
||||
field := val.FieldByName(strmangle.TitleCase(c))
|
||||
if !field.IsValid() {
|
||||
panic(fmt.Sprintf("unable to find field with name: %s\n%#v", strmangle.TitleCase(c), obj))
|
||||
}
|
||||
ret[i*len(columns)+j] = field.Interface()
|
||||
}
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
// GetStructPointers returns a slice of pointers to the matching columns in obj
|
||||
func GetStructPointers(obj interface{}, columns ...string) []interface{} {
|
||||
val := reflect.ValueOf(obj).Elem()
|
||||
|
|
|
@ -352,6 +352,36 @@ func TestGetStructValues(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestGetSliceValues(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
o := []struct {
|
||||
ID int
|
||||
Name string
|
||||
}{
|
||||
{5, "a"},
|
||||
{6, "b"},
|
||||
}
|
||||
|
||||
in := make([]interface{}, len(o))
|
||||
in[0] = o[0]
|
||||
in[1] = o[1]
|
||||
|
||||
vals := GetSliceValues(in, "id", "name")
|
||||
if got := vals[0].(int); got != 5 {
|
||||
t.Error(got)
|
||||
}
|
||||
if got := vals[1].(string); got != "a" {
|
||||
t.Error(got)
|
||||
}
|
||||
if got := vals[2].(int); got != 6 {
|
||||
t.Error(got)
|
||||
}
|
||||
if got := vals[3].(string); got != "b" {
|
||||
t.Error(got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetStructPointers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue