module StyledYAML

Public: A Psych extension to enable choosing output styles for specific objects.

Thanks to Tenderlove for help in <stackoverflow.com/q/9640277/11687>

Examples

data = {
  response: { body: StyledYAML.literal(json_string), status: 200 },
  person: StyledYAML.inline({ 'name' => 'Stevie', 'age' => 12 }),
  array: StyledYAML.inline(%w[ apples bananas oranges ])
}

StyledYAML.dump data, $stdout

Public Class Methods

dump(obj, io = nil, options = {}) click to toggle source

A Psych.dump alternative that uses the custom TreeBuilder

# File lib/locomotive/wagon/tools/styled_yaml.rb, line 106
def self.dump obj, io = nil, options = {}
  real_io = io || StringIO.new(''.encode('utf-8'))
  visitor = YAMLTree.create(options, TreeBuilder.new)
  visitor << obj
  ast = visitor.tree

  begin
    ast.yaml real_io
  rescue
    # The `yaml` method was introduced in later versions, so fall back to
    # constructing a visitor
    Psych::Visitors::Emitter.new(real_io).accept ast
  end

  io ? io : real_io.string
end
inline(obj) click to toggle source

Tag Hashes or Arrays to be output all on one line

# File lib/locomotive/wagon/tools/styled_yaml.rb, line 32
def self.inline obj
  case obj
  when Hash  then obj.extend FlowMapping
  when Array then obj.extend FlowSequence
  else
    warn "#{self}: unrecognized type to inline (#{obj.class.name})"
  end
  return obj
end
literal(obj) click to toggle source

Tag strings to be output using literal style

# File lib/locomotive/wagon/tools/styled_yaml.rb, line 21
def self.literal obj
  obj.extend LiteralScalar
  return obj
end