2009-06-28 63 views
18

代码是否可以在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。但是,截至红宝石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 

回答

6

这丑陋的黑客似乎这样的伎俩......

class Array 
    def to_yaml_style 
    :inline 
    end 
end 

通过Ruby的源浏览,我无法找到任何可以实现的选项。在lib/yaml/constants.rb中描述了默认选项。

+3

仅内嵌小阵列: class Array; def to_yaml_style(); self.length <5? :inline:super;结束 – Costi 2011-06-15 21:22:25

9

关于哈希选项:看到http://yaml4r.sourceforge.net/doc/page/examples.htm

出24:使用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%03d”)当A格式化字符串为锚的ID
ExplicitTypes:发射时使用明确的类型? (默认为false
BestWidth:文本的力折叠发射时:字符宽度折叠文本(默认为80
UseFold当使用? (默认为false
UseBlock:发射时强制所有文本是文字? (默认为false
Encoding:Unicode格式与编码(默认为:Utf8;需要语言Iconv)

+15

不工作。从源头上,我甚至不确定opts散列是否传递给syck。 – anshul 2009-06-29 07:53:46

1

只是指定输出样式的另一种方法,但是这可以根据特定对象而不是全局(例如所有数组)对其进行定制。

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 
相关问题