2009-06-28 112 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 
相關問題