diff options
author | Steve Manuel <nilslice@gmail.com> | 2016-12-20 09:28:51 -0800 |
---|---|---|
committer | Steve Manuel <nilslice@gmail.com> | 2016-12-20 09:28:51 -0800 |
commit | 02b396de26ca7f58b8e8134fbaa098f5af49b911 (patch) | |
tree | e5e14d0d89947ae6a8704f4e28be379262536494 /management/editor/values.go | |
parent | 9b7ee17fe3b43cedb151760215644591a6971d5a (diff) |
splitting up elements file into more logical parts, testing godoc feature;
Diffstat (limited to 'management/editor/values.go')
-rw-r--r-- | management/editor/values.go | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/management/editor/values.go b/management/editor/values.go new file mode 100644 index 0000000..7d71d3f --- /dev/null +++ b/management/editor/values.go @@ -0,0 +1,73 @@ +package editor + +import ( + "fmt" + "reflect" + "strings" +) + +func tagNameFromStructField(name string, post interface{}) string { + // sometimes elements in these environments will not have a name, + // and thus no tag name in the struct which correlates to it. + if name == "" { + return name + } + + field, ok := reflect.TypeOf(post).Elem().FieldByName(name) + if !ok { + panic("Couldn't get struct field for: " + name + ". Make sure you pass the right field name to editor field elements.") + } + + tag, ok := field.Tag.Lookup("json") + if !ok { + panic("Couldn't get json struct tag for: " + name + ". Struct fields for content types must have 'json' tags.") + } + + return tag +} + +// due to the format in which gorilla/schema expects form names to be when +// one is associated with multiple values, we need to output the name as such. +// Ex. 'category.0', 'category.1', 'category.2' and so on. +func tagNameFromStructFieldMulti(name string, i int, post interface{}) string { + tag := tagNameFromStructField(name, post) + + return fmt.Sprintf("%s.%d", tag, i) +} + +func valueFromStructField(name string, post interface{}) string { + field := reflect.Indirect(reflect.ValueOf(post)).FieldByName(name) + + switch field.Kind() { + case reflect.String: + return field.String() + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return fmt.Sprintf("%v", field.Int()) + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return fmt.Sprintf("%v", field.Uint()) + + case reflect.Bool: + return fmt.Sprintf("%t", field.Bool()) + + case reflect.Complex64, reflect.Complex128: + return fmt.Sprintf("%v", field.Complex()) + + case reflect.Float32, reflect.Float64: + return fmt.Sprintf("%v", field.Float()) + + case reflect.Slice: + s := []string{} + + for i := 0; i < field.Len(); i++ { + pos := field.Index(i) + s = append(s, fmt.Sprintf("%v", pos)) + } + + return strings.Join(s, "__ponzu") + + default: + panic(fmt.Sprintf("Ponzu: Type '%s' for field '%s' not supported.", field.Type(), name)) + } +} |