Search code examples
ruby-on-railslayoutcontrollerpartial-viewsclass-instance-variables

Choosing a controller for a layout class instance variable in Rails


I have a DateTime class instance variable @current_year = DateTime.now.year, which I have set into a footer partial. This partial is rendered across several of my clientside pages (and across multiple controllers as <%= render 'layouts/page_footer' %> in the main body of the page - the layout/application.html.erb page is reserved for the site navigation, so the format will not accommodate it there. While I could declare it for every page method it appears on in the controller, I'd find something a little more DRY. Is there a single place I can define my time variable to call in my layout component?


Solution

  • You could add a set_year action in your ApplicationController, something like:

    class ApplicationController < ActionController::Base 
    
      private 
    
        def set_year 
          @current_year = DateTime.now.year
        end
    
    end
    

    And then call it in a before_action in your relevant controller actions. Something like:

    class FooController < ApplicationController
      before_action :set_year, only: [:some_action, :another_action]
    end
    

    Alternatively and riffing off MrYoshiji's comment, you could create a current_year action in ApplicationController, something like:

    class ApplicationController < ActionController::Base
    
      def current_year
        @current_year ||= DateTime.now.year
      end
    
    end
    

    In which case, you could use current_year in your partial instead of @current_year. And then, as MrYoshiji says, you could move that into a helper if that sort of things floats your boat. Something like:

    module ApplicationHelper
    
      def current_year
        @current_year ||= DateTime.now.year
      end
    
    end
    

    The upside, I suppose, of moving current_year into a helper is that it de-clutters your ApplicationController. The downside, I further suppose, is that it obsfucates (to some degree), the source of the current_year action. Again, you'll have to take your boat floating coefficient into consideration.

    BTW, @current_year isn't a DateTime. It's a Fixnum.