Class: RuboCop::Cop::Rails::Date

Inherits:
RuboCop::Cop show all
Includes:
ConfigurableEnforcedStyle
Defined in:
lib/rubocop/cop/rails/date.rb

Overview

This cop checks for the correct use of Date methods, such as Date.today, Date.current etc.

Using ‘Date.today` is dangerous, because it doesn’t know anything about Rails time zone. You must use ‘Time.zone.today` instead.

The cop also reports warnings when you are using ‘to_time` method, because it doesn’t know about Rails time zone either.

Two styles are supported for this cop. When EnforcedStyle is ‘strict’ then the Date methods ‘today`, `current`, `yesterday`, and `tomorrow` are prohibited and the usage of both `to_time` and ’to_time_in_current_zone’ are reported as warning.

When EnforcedStyle is ‘flexible’ then only ‘Date.today` is prohibited and only `to_time` is reported as warning.

Examples:

EnforcedStyle: strict

# bad
Date.current
Date.yesterday
Date.today
date.to_time

# good
Time.zone.today
Time.zone.today - 1.day

EnforcedStyle: flexible (default)

# bad
Date.today
date.to_time

# good
Time.zone.today
Time.zone.today - 1.day
Date.current
Date.yesterday
date.in_time_zone

Constant Summary collapse

MSG =
'Do not use `Date.%<method_called>s` without zone. Use ' \
'`Time.zone.%<day>s` instead.'
MSG_SEND =
'Do not use `%<method>s` on Date objects, because they ' \
'know nothing about the time zone in use.'
BAD_DAYS =
%i[today current yesterday tomorrow].freeze
DEPRECATED_METHODS =
[
  { deprecated: 'to_time_in_current_zone', relevant: 'in_time_zone' }
].freeze
DEPRECATED_MSG =
'`%<deprecated>s` is deprecated. ' \
'Use `%<relevant>s` instead.'

Instance Method Summary collapse

Instance Method Details

#on_const(node) ⇒ Object



64
65
66
67
68
69
70
# File 'lib/rubocop/cop/rails/date.rb', line 64

def on_const(node)
  mod, klass = *node.children
  # we should only check core Date class (`Date` or `::Date`)
  return unless (mod.nil? || mod.cbase_type?) && method_send?(node)

  check_date_node(node.parent) if klass == :Date
end

#on_send(node) ⇒ Object Also known as: on_csend



72
73
74
75
76
77
78
79
80
81
# File 'lib/rubocop/cop/rails/date.rb', line 72

def on_send(node)
  return unless node.receiver && bad_methods.include?(node.method_name)

  return if safe_chain?(node) || safe_to_time?(node)

  check_deprecated_methods(node)

  add_offense(node, location: :selector,
                    message: format(MSG_SEND, method: node.method_name))
end