icon Web设计的Ruby on Rails

第6回 YAML文件处理

Ruby on Rails 业界,相对于 XML 更喜欢将 YAML 作为表现结构化数据的格式。

YAML 是 "YAML Ain't Markup Language" 的缩写。这篇文章中,并没有对 YAML 详细的作法以及与 XML 的区别进行说明。《Rubyist Magazine》的编程的YAML入门(初级篇) 中已经做了非常详细的解说,参照那里就可以了。

下面展示的是表现散列表(关联数组)的 YAML 代码的例子。

name: taro
email: taro@sample.com
age: 39

用Ruby语言表现的话,就是下面这样。

{
  "name" => "taro",
  "email" => "taro@sample.com",
  "age" => 39
}

文件 RAILS_ROOT/tmp/taro.yml 中写入这个 YAML 数据后,载入数据,便生成表示邮件地址的如下代码。

data = YAML.load_file(RAILS_ROOT + "/tmp/taro.yml")
puts data["email"]

非常的简单吧。

理解了的话,就可以在动作中读取外部 YAML 文件,并传递到模板。例如,有一个 RAILS_ROOT/data/table1.yml 文件,作如下书写。

-
  name: taro
  email: taro@sample.com
  age: 39
-
  name: jiro
  email: jiro@sample.com
  age: 35
-
  name: saburo
  email: saburo@sample.com
  age: 31

然后决定模板 show.rhtml 的样式。

<table border="1" cellpadding="4">
  <tr>
    <th>姓名</th>
    <th>邮箱地址</th>
    <th>年龄</th>
  </tr>
<% @records.each do |record| -%>
  <tr>
    <td><%= record['name'] %></td>
    <td><%= record['email'] %></td>
    <td><%= record['age'] %></td>
  </tr>
<% end -%>
</table>

show 动作如下。

class TablesController < ActionController
  def show
    id = params[:id]
    @records = YAML.load_file(RAILS_ROOT + "/data/table#{id}.yml")
  end
end

用浏览器在 http://localhost:3000/tables/show/1 搜索的话,应该会显示下面内容。

姓名邮箱地址年龄
tarotaro@sample.com39
jirojiro@sample.com35
saburosaburo@sample.com31

下一章对大家较 YAML 更熟悉的 CSV 文件进行说明。通过 CSV 格式载入 Microsoft Excel 数据,生成 Web 网页。

(2007/12/03)