[ACCEPTED]-Is it possible to specify formatting options for to_yaml in ruby?-yaml
About the hash options: see http://yaml4r.sourceforge.net/doc/page/examples.htm
Ex. 24: Using 16 to_yaml
with an options Hash
puts [[ 'Crispin', 'Glover' ]].to_yaml( :Indent => 4, :UseHeader => true, :UseVersion => true )
# prints:
# --- %YAML:1.0
# -
# - Crispin
# - Glover
Ex. 25: Available symbols 15 for an options Hash
Indent
: The default indentation 14 to use when emitting (defaults to2
)
Separator
: The 13 default separator to use between documents 12 (defaults to'---'
)
SortKeys
: Sort Hash keys when emitting? (defaults 11 tofalse
)
UseHeader
: Display the YAML header when emitting? (defaults 10 tofalse
)
UseVersion
: Display the YAML version when emitting? (defaults 9 tofalse
)
AnchorFormat
: A formatting string for anchor 8 IDs when emitting (defaults to 'id%03d
')
ExplicitTypes
: Use 7 explicit types when emitting? (defaults 6 tofalse
)
BestWidth
: The character width to use when 5 folding text (defaults to80
)
UseFold
: Force folding 4 of text when emitting? (defaults tofalse
)
UseBlock
: Force 3 all text to be literal when emitting? (defaults 2 tofalse
)
Encoding
: Unicode format to encode with (defaults 1 to:Utf8
; requires Iconv)
Starting from Ruby 1.9 psych
is used as a default 2 YAML engine. It supports some attributes: http://ruby-doc.org/stdlib-2.1.0/libdoc/psych/rdoc/Psych/Handler/DumperOptions.html
So 1 for me it works:
irb(main):001:0> require 'yaml'
=> true
irb(main):002:0> puts [{'a'=> 'b', 'c'=> 'd'}, {'e'=> 'f', 'g'=>'h'}].to_yaml(:indentation => 4)
---
- a: b
c: d
- e: f
g: h
This ugly hack seems to do the trick...
class Array
def to_yaml_style
:inline
end
end
Browsing 3 through ruby's source, I can't find any 2 options I could pass to achieve the same. Default 1 options are described in the lib/yaml/constants.rb.
Just another hack to specify the output 3 style, but this one allows to customize 2 it per specific object, instead of globally 1 (e.g. for all arrays).
https://gist.github.com/jirutka/31b1a61162e41d5064fc
Simple example:
class Movie
attr_accessor :genres, :actors
# method called by psych to render YAML
def encode_with(coder)
# render array inline (flow style)
coder['genres'] = StyledYAML.inline(genres) if genres
# render in default style (block)
coder['actors'] = actors if actors
end
end
The latest versions of Ruby use the Psych 4 module for YAML parsing. There aren't many 3 options that you can pass but you can change 2 indention and line width. Check the latest 1 Psych documentation for more details.
Use Psych directly.
Indentation has no effect:
my_yaml.to_yaml(:indentation => 2)
Indentation 1 works:
Psych.dump(my_yaml, :indentation => 8)
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.