module StyledYAML

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

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

Example:

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

double_quoted(str) click to toggle source

Tag string to be output using double quoted style.

# File lib/styled_yaml.rb, line 132
def self.double_quoted(str)
  str.extend(DoubleQuotedScalar)
  str
end
dump(obj, io = nil, options = {}) click to toggle source

A Psych.dump alternative that uses the custom TreeBuilder

# File lib/styled_yaml.rb, line 151
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 || real_io.string
end
folded(str) click to toggle source

Tag string to be output using folded style.

# File lib/styled_yaml.rb, line 120
def self.folded(str)
  str.extend(FoldedScalar)
  str
end
inline(obj) click to toggle source

Tag Hash or Array to be output all on one line.

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

Tag string to be output using literal style.

# File lib/styled_yaml.rb, line 114
def self.literal(str)
  str.extend(LiteralScalar)
  str
end
single_quoted(str) click to toggle source

Tag string to be output using single quoted style.

# File lib/styled_yaml.rb, line 126
def self.single_quoted(str)
  str.extend(SingleQuotedScalar)
  str
end