Rails-flavored Ruby
這個章節是要介紹一下 Ruby
在這個 app/views/layouts/application.html.rb 裡面:
<!DOCTYPE html>
<html>
<head>
<title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
<%= stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
其中這段:
<%= stylesheet_link_tag "application", media: "all",
"data-turbolinks-track" => true %>
這行使用 Rails 內建的方法 stylesheet_link_tag 載入 application.css(包括所有 media types,computer screens and printers)。
這行程式碼起碼有四件事需要知道:
- 內建的 Rails 方法(method)
- 調用方法時不需要括號
- symble
- Hash
Rails 除了有很多內建方法可以在 views 中使用,你也可以自訂方法,稱作輔助方法(helpers)。
剛剛上面 app/views/layouts/application.html.rb 其中有一行是:
<%= yield(:title) %> | Ruby on Rails Tutorial Sample App
這行的意思就是要求每個 view 中都要使用 provide 方法提供標題:
<% provide(:title, "Home") %>
<h1>Sample App</h1>
<p>
This is the home page for the
<a href="http://www.railstutorial.org/">Ruby on Rails Tutorial</a>
sample application.
</p>
如果沒有提供標題的話,標題會變成這樣,前面有一條時尚的直線:
| Ruby on Rails Tutorial Sample App
這時候可以自訂輔助方法:
- 如果沒有提供標題,那就使用「Ruby on Rails Tutorial Sample App」
- 如果有提供標題,那就是使用「<標題> | Ruby on Rails Tutorial Sample App」
在 app/helpers/application_helper.rb 自訂一個輔助方法:
module ApplicationHelper
def full_title(page_title = '')
base_title = "Ruby on Rails Tutorial Sample App"
if page_title.empty?
base_title
else
base_title = page_title + " | " + base_title
end
end
end
然後接著修改 app/views/layouts/application.html.rb 那行:
<title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
改成:
<title><%= full_title(yield(:title)) %></title>
然後就可以把 app/views/static_pages/home.html.erb 標題中的「Home」拿掉,為此先來修改測試 test/controllers/static_pages_controller_test.rb,確認首頁不會出現「Home」:
require 'test_helper'
class StaticPagesControllerTest < ActionController::TestCase
test "should get home" do
..
..
assert_select "title", "Ruby on Rails Tutorial Sample App"
end
..
..
end
執行測試,失敗 (Red):
$ rake test
3 tests, 6 assertions, 1 failures, 0 errors, 0 skips
再去 app/views/static_pages/home.html.erb 拿掉 provide 那行,變成:
<h1>Sample App</h1>
<p>
This is the home page for the
<a href="http://www.railstutorial.org/">Ruby on Rails Tutorial</a>
sample application.
</p>
再執行測試,測試就會通過了。
在前面的 full_title 輔助方法中,其中:
module ApplicationHelper
module 提供一種把相關的方法組織在一起的方式,所以可以使用 include 把 module 插入到其他 class 中。Rails 會幫你引入輔助方法的 module,所以 full_title 可以自動地在任何 view 中使用。