Categories
Programming Rails Ruby

YAML 簡介

Rails 的資料庫設定檔 database.yml 是用一種叫 YAML 的格式所撰寫,檔案打開來,看起來就像一般的 plain 設定檔,非常容易修改。

YAML 的設計首要目標就是要讓使用者容易看懂,可以和 script 語言搭配良好。用途有 資料序列化 data serialization、設定檔 configuration settings、log files、Internet messaging、filtering 等。網站上已知有支援的 script 語言有 Python,Ruby,Java,PHP,Perl,Javascript 等。

參考資料:

一個範例,其中

invoice: 34843
date   : 2001-01-23
bill-to: &id001
    given  : Chris
    family : Dumars
    address:
        lines: |
            458 Walkman Dr.
            Suite #292
        city    : Royal Oak
        state   : MI
        postal  : 48046
ship-to: *id001
product:
    – sku         : BL394D
      quantity    : 4
      description : Basketball
      price       : 450.00
    – sku         : BL4438H
      quantity    : 1
      description : Super Hoop
      price       : 2392.00
tax  : 251.42
total: 4443.52
comments: >
    Late afternoon is best.
    Backup contact is Nancy
    Billsmer @ 338-4338.

用 Ruby 讀進資料

require ‘yaml’

ps2 = YAML.load_file(‘y.yaml’)
ps2.each do |it|
  puts it.inspect
end

讀出來 inspect 的結果是

[“tax”, 251.42]

[“bill-to”, {
      “given”=>”Chris”,
       “family”=>”Dumars”,
        “address”=> {
            “postal”=>48046,
             “city”=>”Royal Oak”,
             “lines”=>”458 Walkman Dr.\nSuite #292\n”,
             “state”=>”MI”}
}]

[“comments”, “Late afternoon is best. Backup contact is Nancy Billsmer @ 338-433
8.\n”]

[“invoice”, 34843]

[“date”, #]

[“total”, 4443.52]

[“product”,
      [
         {“price”=>450.0, “quantity”=>4, “description”=>”Basketball”, “sku”=
>”BL394D”},
         {“price”=>2392.0, “quantity”=>1, “description”=>”Super Hoop”, “sku”=
>”BL4438H”}
     ]
]

[“ship-to”, {“given”=>”Chris”, “family”=>”Dumars”, “address”=>{“postal”=>48046,
“city”=>”Royal Oak”, “lines”=>”458 Walkman Dr.\nSuite #292\n”, “state”=>”MI”}}]

Rails Receipts 一書提到你可以這樣運用在 database.yml :

defaults: &defaults
  adapter: mysql
  username: root
  password: abcdef
  socket: /tmp/mysql.sock

development:
  database: xxx_development
  < <: *defaults

test:
  database: xxx_test
  <<: *defaults

production:
  database: xxx_productuin
  <<: *defaults

這樣的話,都會使用一樣的帳號密碼設定啦。

Leave a Reply

Your email address will not be published. Required fields are marked *