Skip to content

Instantly share code, notes, and snippets.

@TheRusskiy
Created October 1, 2016 20:01
Show Gist options
  • Save TheRusskiy/1a3949b55fdb3a82c5c007ec1273c612 to your computer and use it in GitHub Desktop.
Save TheRusskiy/1a3949b55fdb3a82c5c007ec1273c612 to your computer and use it in GitHub Desktop.
Smart page titles in Rails
class ApplicationController < ActionController::Base
before_filter :set_page_title
CONTROLLER_TITLES = Hash.new
# for setting page titles for the whole controller
def self.page_title title
CONTROLLER_TITLES[self.name] = title
end
# for setting page titles for a specific actions.
# this overrides @page_title previously set in before_filter
def page_title title
@page_title = title
end
private
def set_page_title
@page_title = CONTROLLER_TITLES[self.class.name] || controller_implicit_title
end
def controller_implicit_title
@@controller_implicit_titles ||= Hash.new
# remove any namespaces and mentions of controller
# so Client::OrdersController becomes "Orders"
@@controller_implicit_titles[self.class.name] ||= (self.class.name.gsub(/(.+::)/, '').gsub('Controller', '').underscore.gsub('_', ' ').titleize
end
end
<!DOCTYPE html>
<html>
<head>
<title><%= @page_title || 'My Awesome App'%></title>
</head>
<body>
<%= yield %>
</body>
class OrderNotesController < ApplicationController
def index # Page title == 'Order Notes'
@note = OrderNote.all
end
def order # Page title == 'Notes for Order #12345'
page_title = "Notes for Order ##{params[:order_id]}"
@note = OrderNote.where(order_id: params[:order_id])
end
end
class OrdersController < ApplicationController
page_title 'Orders' # unless specified otherwise all pages are gonna have title 'Orders"
def index # Page title == 'Orders'
@orders = Order.all
end
def cancelled # Page title == 'Cancelled Orders'
page_title 'Cancelled Orders'
@orders = Order.cancelled
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment