A way to build <title>

I would like to be able to easily build a <title> string. Here is how I am doing it right now (I have omitted parts not relevant):

In the layout:

<title><%= title %></title>

Which calls:

module ApplicationHelper

    def title         @title_parts.join ' | '     end

end

and @title_parts is build like so:

class ApplicationController < ActionController::Base

    before_filter :prepare_views

    protected

    def prepare_views         # other stuff         prepend_title t :pnc     end

    def prepend_title item         @title_parts ||=         @title_parts.insert 0, item     end

end

class DashboardController < ApplicationController

    before_filter :prepare_title

    def index         prepend_title t :home     end

    protected

    def prepare_title         prepend_title t :dashboard     end end

How might I clean this up? My ideal would be for each controller to be able to call "title" setting its part of the title, and for individual actions to manually prepend their title part:

class ApplicationController

    title t :pnc

end

class DashboardController

    title t :dashboard

    def index         prepend_title :home     end

end

Such an approach presents some problems, the first being that "t" is not available in the class scope. So I'm a bit stuck here.

Thomas

Hi Thomas,

How might I clean this up? My ideal would be for each controller to be able to call "title" setting its part of the title, and for individual actions to manually prepend their title part:

You may have a look to this screencast from Ryan Bates :

Pretty clean and efficient!

Hope it helps :wink:

@lex

Thanks, that seems to be the right idea. Here's what I ultimately settled on...the following results in "Home | Dashboard | PNC" for a request to DashboardController#index.

class ApplicationController < ActionController::Base

  def self.title item     before_filter do |controller|       controller.instance_eval do         title item       end     end   end

  title :pnc

  def initialize     @title_parts =     super   end

  protected

  def title item     @title_parts.insert 0, item   end

end

module ApplicationHelper

  def title     @title_parts.map { |part|       t part     }.join ' | '   end

end

class DashboardController < ApplicationController

  title :dashboard

  def index     title :home   end

end

<title><%= title %></title>

Thomas