如何正确设计to_yaml样式

时间:2012-03-02 16:49:37

标签: ruby methods formatting yaml to-yaml

我想存储一些关于几个应用程序的配置信息,这样我就可以创建一个'app drawer'。我将信息存储在一个看起来像这样的数组中 -

[["page_view", {"path"=>"somepath/asdf/asdf", "name"=>"Page View"}], ["outage_impact", {"path"=>"newpath/asdf/asdf", "name"=>"Outage Impact"}]]

但是当我在这个数组上使用to_yaml时,我得到了这个输出:

--- 
- - page_view
  - path: somepath/asdf/asdf
    name: Page View
- - outage_impact
  - path: newpath/asdf/asdf
    name: Outage Impact 

理想情况下,我想要更像这样的东西:

page_view
  path: somepath/af/asdf
  name: blah
outage_impact
  name: blah
  path: adsf/adsf/asdf

我尝试在to_yaml方法上找到更多信息,但它很少见。我认为我的阵列可能需要格式化不同,但我一直猜测并检查一段时间无济于事。

我是否应该使用to_yaml方法或者其他方法是否更好?

1 个答案:

答案 0 :(得分:1)

将其转换为哈希,然后使用to_yaml将为您的示例提供类似的输出(但在开始时使用---

arr = [["page_view", {"path"=>"somepath/asdf/asdf", "name"=>"Page View"}], ["outage_impact", {"path"=>"newpath/asdf/asdf", "name"=>"Outage Impact"}]]

puts Hash[*arr.flatten].to_yaml

给出:

---
page_view:
  path: somepath/asdf/asdf
  name: Page View
outage_impact:
  path: newpath/asdf/asdf
  name: Outage Impact