Created
July 9, 2013 19:47
-
-
Save anonymous/5960637 to your computer and use it in GitHub Desktop.
An example of how to range over collections with gypsy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Range runs the given closure on each element of the given list or map. If | |
// the directive identifies a map, idx will be 0. The index or key will be set | |
// to the appropriate values for a list or map, respectively, and the other | |
// will be zero. | |
// | |
// Example: | |
// config.Range("servers", func(i int, _ string, n node) { | |
// fmt.Printf("server[%d] = %q\n", i, n.(Scalar).String()) | |
// }) | |
// config.Range("users", func(_ int, name string, n node) { | |
// fmt.Printf("user[%q] = %#v\n", name, n) | |
// }) | |
func Range(directive string, each func(idx int, key string, node yaml.Node)) error { | |
node, err := yaml.Child(global.Root, directive) | |
if err != nil { | |
return fmt.Errorf("no such directive: %q: %s", directive, err) | |
} | |
switch n := node.(type) { | |
case yaml.List: | |
for i, v := range n { | |
each(i, "", v) | |
} | |
case yaml.Map: | |
for k, v := range n { | |
each(0, k, v) | |
} | |
default: | |
return fmt.Errorf("%q is not a sequence or mapping (%T)", directive, n) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment