Dumper.coffee 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. Utils = require './Utils'
  2. Inline = require './Inline'
  3. # Dumper dumps JavaScript variables to YAML strings.
  4. #
  5. class Dumper
  6. # The amount of spaces to use for indentation of nested nodes.
  7. @indentation: 4
  8. # Dumps a JavaScript value to YAML.
  9. #
  10. # @param [Object] input The JavaScript value
  11. # @param [Integer] inline The level where you switch to inline YAML
  12. # @param [Integer] indent The level of indentation (used internally)
  13. # @param [Boolean] exceptionOnInvalidType true if an exception must be thrown on invalid types (a JavaScript resource or object), false otherwise
  14. # @param [Function] objectEncoder A function to serialize custom objects, null otherwise
  15. #
  16. # @return [String] The YAML representation of the JavaScript value
  17. #
  18. dump: (input, inline = 0, indent = 0, exceptionOnInvalidType = false, objectEncoder = null) ->
  19. output = ''
  20. prefix = (if indent then Utils.strRepeat(' ', indent) else '')
  21. if inline <= 0 or typeof(input) isnt 'object' or input instanceof Date or Utils.isEmpty(input)
  22. output += prefix + Inline.dump(input, exceptionOnInvalidType, objectEncoder)
  23. else
  24. if input instanceof Array
  25. for value in input
  26. willBeInlined = (inline - 1 <= 0 or typeof(value) isnt 'object' or Utils.isEmpty(value))
  27. output +=
  28. prefix +
  29. '-' +
  30. (if willBeInlined then ' ' else "\n") +
  31. @dump(value, inline - 1, (if willBeInlined then 0 else indent + @indentation), exceptionOnInvalidType, objectEncoder) +
  32. (if willBeInlined then "\n" else '')
  33. else
  34. for key, value of input
  35. willBeInlined = (inline - 1 <= 0 or typeof(value) isnt 'object' or Utils.isEmpty(value))
  36. output +=
  37. prefix +
  38. Inline.dump(key, exceptionOnInvalidType, objectEncoder) + ':' +
  39. (if willBeInlined then ' ' else "\n") +
  40. @dump(value, inline - 1, (if willBeInlined then 0 else indent + @indentation), exceptionOnInvalidType, objectEncoder) +
  41. (if willBeInlined then "\n" else '')
  42. return output
  43. module.exports = Dumper