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?

- 541
- 4
- 20
2 Answers
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
.

- 19,953
- 5
- 31
- 44
-
1or a helper, kind of like how `current_user` is defined: `def current_year ; @current_year ||= DateTime.now.year ; end` in the `ApplicationHelper`. – MrYoshiji Mar 28 '18 at 15:26
you could create a method in application_helper.rb file and use it anywhere you like.
def current_year
@current_year = DateTime.now.year
end

- 19,953
- 5
- 31
- 44

- 800
- 4
- 10
-
I used the other one since my boat floating coefficient has to factor in sourcing and junior devs not necessarily being familiar with helpers, but I really like this answer for future purposes! My current Application controller is two methods long, so in this case not so much an issue. :) – Boucherie Mar 28 '18 at 17:44