LoginSignup
7
12

More than 3 years have passed since last update.

【Rails】provideとyieldを使ったページタイトルの設定【Rails Tutorial 3・4・5章まとめ】

Last updated at Posted at 2019-11-26

各ページのビューにprovideを記述

app/views/static_pages/home.html.erb
<% provide(:title, "Home") %>
<h1>Sample App</h1>

appilication.htmlのtitleにyieldを記述

app/views/layouts/application.html.erb
  <head>
    <title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
  </head>

ページタイトルに対するテスト

test/controllers/static_pages_controller_test.rb
  def setup
    @base_title = "Ruby on Rails Tutorial Sample App"
  end

 test "should get home" do
    get static_pages_home_url
    assert_response :success
    assert_select "title", "Home | #{@base_title}"
  end

assert_selectを使って、titlesセレクタがページタイトルと一致することを確認する。
ページタイトルの重複部分はsetup内の変数@base_titleに入れておく。

~ここから4章~

full_titleヘルパーを作成

rootであるhomeビューでは、アプリケーション名のみをタイトルに表示したい。
そのため、homeビューではprovideは不要である。
しかし、この場合タイトルが「 | Ruby on Rails Tutorial Sample App」となり、余計な|が入る。
これを修正するためにページタイトルを返すfull_titleヘルパーを作成する。

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
      page_title + " | " + base_title
    end
  end

end
app/views/layouts/application.html.erb
<html>
  <head>
    <title><%= full_title(yield(:title)) %></title>
  </head>

変数page_titleの初期値を空にしておき、provideからくる引数yield(:title)が与えられなければ、base_titleのみを表示する。
与えられれば、|を追加して、完全なタイトルを表示する。
(ちなみに、empty?メソッドの末尾の?は、論理値を返すメソッドであることを意味する)

homeビューからはprovideを消しておく。

app/views/static_pages/home.html.erb
<h1>Sample App</h1>

「home」という文字はもうタイトルには無いので、テストを修正しておく。

test/controllers/static_pages_controller_test.rb
  test "should get home" do
    get static_pages_home_url
    assert_response :success
    assert_select "title", @base_title
  end

〜ここから5章〜

full_titleヘルパーのテスト

タイトルに誤字などがないか、正しく機能しているかどうかをテストする。

applicationヘルパーにあるfull_titleヘルパーはそのままではテストで使えないので、includeを使ってテストで使えるようにする。

test/test_helper.rb
class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all
  # Add more helper methods to be used by all tests here...
  include ApplicationHelper
end
test/helpers/application_helper_test.rb
require 'test_helper'

class ApplicationHelperTest < ActionView::TestCase
  test "full title helper" do
    assert_equal full_title,         "Ruby on Rails Tutorial Sample App"
    assert_equal full_title("Help"), "Help | Ruby on Rails Tutorial Sample App"
  end
end

asseet_equalは第一引数と第二引数が等しいかどうかを確認するために使用する。

ところで、test/helpers/application_helper_test.rbは自動で生成されないようである。

7
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
12