是否可以在ruby中为to_yaml指定格式化选项?
代码
require 'yaml' puts YAML.load(" is_something: values: ['yes', 'no'] ").to_yaml
产生
--- is_something: values: - "yes" - "no"
虽然这是一个正确的yaml,但是当你有一个数组哈希时它看起来很丑陋。 有没有办法让to_yaml
生成yaml的内联数组版本?
可以将选项哈希传递给to_yaml
但是如何使用它呢?
编辑0:感谢PozsárBalázs。 但是,从ruby 1.8.7(2009-04-08 patchlevel 160)开始,选项哈希不像宣传的那样工作。 🙁
irb irb(main):001:0> require 'yaml' => true irb(main):002:0> puts [[ 'Crispin', 'Glover' ]].to_yaml( :Indent => 4, :UseHeader => true, :UseVersion => true ) --- - - Crispin - Glover => nil
关于哈希选项:请参阅http://yaml4r.sourceforge.net/doc/page/examples.htm
防爆。 24:使用带有选项Hash的to_yaml
puts [[ 'Crispin', 'Glover' ]].to_yaml( :Indent => 4, :UseHeader => true, :UseVersion => true ) # prints: # --- %YAML:1.0 # - # - Crispin # - Glover
防爆。 25:选项哈希的可用符号
Indent
:发出时使用的默认缩进(默认为2
)
Separator
:文档之间使用的默认分隔符(默认为'---'
)
SortKeys
:发出时排序哈希键? (默认为false
)
UseHeader
:发出时显示YAML标题? (默认为false
)
UseVersion
:发出时显示YAML版本? (默认为false
)
AnchorFormat
:发出时锚点ID的格式字符串(默认为’id%03d
‘)
ExplicitTypes
:发出时使用显式类型? (默认为false
)
BestWidth
:折叠文本时使用的字符宽度(默认为80
)
UseFold
:发出时强制折叠文本? (默认为false
)
UseBlock
:强制所有文本在发出时都是文字的? (默认为false
)
Encoding
:要编码的Unicode格式(默认为:Utf8
;需要Iconv)
这个丑陋的黑客似乎成功了……
class Array def to_yaml_style :inline end end
浏览ruby的源代码,我找不到任何我可以通过的选项来实现相同的目标。 lib / yaml / constants.rb中描述了默认选项。
从Ruby 1.9开始, psych
被用作默认的YAML引擎。 它支持一些属性: http : //ruby-doc.org/stdlib-2.1.0/libdoc/psych/rdoc/Psych/Handler/DumperOptions.html
所以对我来说它有效:
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
只是另一个指定输出样式的hack,但是这个允许根据特定对象自定义它,而不是全局(例如对于所有数组)。
https://gist.github.com/jirutka/31b1a61162e41d5064fc
简单的例子:
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
- Ruby selenium webdriver无法找到Mozilla geckodriver
- uninitialized constant> ActionCable :: Server :: Configuration :: ApplicationCable
- 使用rails计划任务
- 如何在Rails中显示URL指向的图像
- 如何使用script / rails generate添加新操作和视图?
- 更改嵌套哈希值
- rails – postgres错误:原因:库版本不兼容:libpq.5.dylib需要1.0.0或更高版本,
- 如何使validates_inclusion_of的错误消息显示允许的选项列表?
- 在rails中解析日期