structure: add omitnested support to values

This commit is contained in:
Fatih Arslan 2014-08-07 21:57:51 +03:00
parent 137635f5eb
commit eacf1a7590
2 changed files with 45 additions and 1 deletions

View File

@ -44,6 +44,7 @@ func Map(s interface{}) map[string]interface{} {
// map[string]interface{} too
finalVal = Map(val.Interface())
} else {
finalVal = val.Interface()
}
@ -66,9 +67,13 @@ func Values(s interface{}) []interface{} {
v, fields := strctInfo(s)
t := make([]interface{}, 0)
for _, field := range fields {
val := v.FieldByName(field.Name)
if IsStruct(val.Interface()) {
_, tagOpts := parseTag(field.Tag.Get(DefaultTagName))
if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") {
// look out for embedded structs, and convert them to a
// []interface{} to be added to the final values slice
for _, embeddedVal := range Values(val.Interface()) {

View File

@ -278,6 +278,45 @@ func TestValues(t *testing.T) {
}
}
func TestValues_OmitNested(t *testing.T) {
type A struct {
Name string
Value int
}
a := A{
Name: "example",
Value: 123,
}
type B struct {
A A `structure:",omitnested"`
C int
}
b := &B{A: a, C: 123}
s := Values(b)
if len(s) != 2 {
t.Errorf("Values of omitted nested struct should be not counted")
}
inSlice := func(val interface{}) bool {
for _, v := range s {
if reflect.DeepEqual(v, val) {
return true
}
}
return false
}
for _, val := range []interface{}{123, a} {
if !inSlice(val) {
t.Errorf("Values should have the value %v", val)
}
}
}
func TestValues_Nested(t *testing.T) {
type A struct {
Name string