Smart page titles in Ruby on Rails

Having separate titles for each page in Rails application is a very common requirement and yet RoR does not provide any built in ways to deal with it. I am going to present you with some handy code that can solve this problem without use of gems.

There are going to be 3 ways to define a page title:

  • For tho whole controller.
  • For a specific action inside a controller.
  • Implicitly from a controller name.
Last is gonna be especially useful, you can just drop the following code into your application and have reasonably good titles.

So lets add code to our parent ApplicationController:

And reference page title in our layout:

After that setting pages titles is extremely easy. You don't even have to do it if you are naming your controllers properly.

Popular posts from this blog

Next.js: restrict pages to authenticated users

HTTP server in Ruby 3 - Fibers & Ractors

Using image loader is Next.js