Module: Protopack::StyledYAML
- Defined in:
- lib/protopack/styled_yaml.rb
Overview
Public: A Psych extension to enable choosing output styles for specific objects.
Thanks to Tenderlove for help in <stackoverflow.com/q/9640277/11687>
Gist: gist.github.com/mislav/2023978
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
Defined Under Namespace
Modules: FlowMapping, FlowSequence, LiteralScalar Classes: TreeBuilder, YAMLTree
Class Method Summary collapse
-
.dump(obj, io = nil, options = {}) ⇒ Object
A Psych.dump alternative that uses the custom TreeBuilder.
-
.inline(obj) ⇒ Object
Tag Hashes or Arrays to be output all on one line.
-
.literal(obj) ⇒ Object
Tag strings to be output using literal style.
Class Method Details
.dump(obj, io = nil, options = {}) ⇒ Object
A Psych.dump alternative that uses the custom TreeBuilder
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
# File 'lib/protopack/styled_yaml.rb', line 108 def self.dump obj, io = nil, = {} real_io = io || StringIO.new(''.encode('utf-8')) visitor = YAMLTree.new(, 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) ⇒ Object
Tag Hashes or Arrays to be output all on one line
34 35 36 37 38 39 40 41 42 |
# File 'lib/protopack/styled_yaml.rb', line 34 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) ⇒ Object
Tag strings to be output using literal style
23 24 25 26 |
# File 'lib/protopack/styled_yaml.rb', line 23 def self.literal obj obj.extend LiteralScalar return obj end |