Chiperific
Chiperific

Reputation: 4686

M Hartl's Ruby on Rails Tutorial Chapter 5 custom title on home page

In Michael Hartl's RoR tutorial: the exercises at the end of chapter 5 involve simplifying RSpec tests.

5.37 ( http://ruby.railstutorial.org/chapters/filling-in-the-layout#sec-layout_exercises ) defines several test for the home page. In the file 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

For this test to pass, I need to have the Home page title display: "Ruby on Rails Tutorial Sample App" And not "Ruby on Rails Tutorial Sample App | Home"

But, the tutorial doesn't walk me through how to code that change.

Here's what I've tried:

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

  1. Remove:

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

In app/views/layouts/application.html.erb Edit the tag to:

<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>

And other variations my noob brain could muster. Here's what I'm trying to accomplish:

If the page has no title provided, return "Ruby on Rails Tutorial Sample App"

If there is a title provided, return "Ruby on Rails Tutorial Sample App | #PageTitle"

Any suggestions are appreciated.

Upvotes: 1

Views: 1268

Answers (1)

wrhall
wrhall

Reputation: 1308

What about this?

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

Just call the method inside your view. So it should be something like <title><%= full_title(yield(:title)) %></title> as he says.

Upvotes: 6

Related Questions