| OLD | NEW |
| (Empty) |
| 1 /** | |
| 2 * This library is used to convert data from a map to a YAML string. | |
| 3 */ | |
| 4 library dart2yaml; | |
| 5 | |
| 6 /** | |
| 7 * Gets a String representing the input Map in YAML format. | |
| 8 */ | |
| 9 String getYamlString(Map documentData) { | |
| 10 StringBuffer yaml = new StringBuffer(); | |
| 11 _addLevel(yaml, documentData, 0); | |
| 12 return yaml.toString(); | |
| 13 } | |
| 14 | |
| 15 /** | |
| 16 * This recursive function adds to its input StringBuffer and builds | |
| 17 * a YAML string from the input Map. | |
| 18 */ | |
| 19 // TODO(tmandel): Fix quotes with String objects. | |
| 20 void _addLevel(StringBuffer yaml, Map documentData, int level) { | |
| 21 documentData.keys.forEach( (key) { | |
| 22 _calcSpaces(level, yaml); | |
| 23 yaml.write("\"$key\" : "); | |
| 24 | |
| 25 if (documentData[key] is Map) { | |
| 26 yaml.write("\n"); | |
| 27 _addLevel(yaml, documentData[key], level + 1); | |
| 28 | |
| 29 } else if (documentData[key] is List) { | |
| 30 var elements = documentData[key]; | |
| 31 yaml.write("\n"); | |
| 32 elements.forEach( (element) { | |
| 33 if (element is Map) { | |
| 34 _addLevel(yaml, element, level + 1); | |
| 35 } else { | |
| 36 _calcSpaces(level + 1, yaml); | |
| 37 yaml.write("- ${_processElement(element)}"); | |
| 38 } | |
| 39 }); | |
| 40 | |
| 41 } else { | |
| 42 yaml.write(_processElement(documentData[key])); | |
| 43 } | |
| 44 }); | |
| 45 } | |
| 46 | |
| 47 /** | |
| 48 * Returns an escaped String form of the inputted element. | |
| 49 */ | |
| 50 String _processElement(var element) { | |
| 51 return "\"${element.toString().replaceAll("\"", "\\\"")}\"\n"; | |
| 52 } | |
| 53 | |
| 54 /** | |
| 55 * Based on the depth in the file, this function returns the correct spacing | |
| 56 * for an element in the YAML output. | |
| 57 */ | |
| 58 void _calcSpaces(int spaceLevel, StringBuffer yaml) { | |
| 59 for (int i = 0; i < spaceLevel; i++) { | |
| 60 yaml.write(" "); | |
| 61 } | |
| 62 } | |
| OLD | NEW |