1

Michael Hartl の RoR チュートリアル: 第 5 章の最後の演習には、RSpec テストの単純化が含まれます。

5.37 ( http://ruby.railstutorial.org/chapters/filling-in-the-layout#sec-layout_exercises ) では、ホームページのいくつかのテストが定義されています。ファイル spec/helpers/application_helper_spec.rb 内:

require 'spec_helper'

describe ApplicationHelper do

  describe "full_title" do
  .
  .
  .
  .
    it "should not include a bar for the home page" do
      full_title("").should_not =~ /\|/
    end
  end
end

このテストに合格するには、ホームページのタイトルを「Ruby on Rails Tutorial Sample App | Home」ではなく「Ruby on Rails Tutorial Sample App」と表示する必要があります。

ただし、このチュートリアルでは、その変更をコーディングする方法について説明していません。

これが私が試したことです:

app/views/static_pages/home.html.erb:

  1. 削除する:

    <% provide(:title, 'Home') %>

app/views/layouts/application.html.erb で、タグを次のように編集します。

<title>
 <% if :title
  full_title = "Ruby on Rails Tutorial Sample App | " && yield(:title)
 else
  full_title = "Ruby on Rails Tutorial Sample App"
 end %>
 <%= print full_title %>
</title>

そして、私の初心者の脳が召集できる他のバリエーション。これが私が達成しようとしていることです:

ページにタイトルが指定されていない場合は、「Ruby on Rails チュートリアル サンプル アプリ」を返します。

タイトルが提供されている場合は、「Ruby on Rails チュートリアル サンプル アプリ | #PageTitle」を返します。

任意の提案をいただければ幸いです。

4

1 に答える 1

6

これはどうですか?

module ApplicationHelper

  # Returns the full title on a per-page basis.
  def full_title(page_title)
    base_title = "Ruby on Rails Tutorial Sample App"
    if page_title.empty?
      base_title
    else
      "#{base_title} | #{page_title}"
    end
  end
end

http://ruby.railstutorial.org/chapters/rails-flavored-ruby#code-title_helper

ビュー内でメソッドを呼び出すだけです。<title><%= full_title(yield(:title)) %></title> ですから、彼の言うようになるはず です。

于 2012-12-05T20:12:19.937 に答える