ruby-on-railsrubydate

Current year in Ruby on Rails


How can I get current year in Ruby on Rails?

I tried a variety of things, including

The problem is they return the previous year in cases where year changes after launching the server (eg. after new year's).

Relevant code:

Model brewery.rb

class Brewery < ActiveRecord::Base
...
validates :year, numericality: { only_integer: true, less_than_or_equal_to: Date.today.year }
...

Problem occurs when creating a new brewery, so I assumed Date.today.year would be evaluated whenever that action takes place.


Solution

  • In your example, Date.today.year is evaluated only once when the application is started and the class is loaded and therefore doesn't change any more later on.

    But when you use a lambda in your validator declaration, then the lambda is evaluated each time when the validation is checked for that attribute:

    validates :year, numericality: { 
      only_integer: true, 
      less_than_or_equal_to: ->(_brewery) { Date.current.year }
    }
    

    Furthermore, I suggest using Date.current instead of Date.today because the current method pays attention to timezone settings.