Class: RuboCop::Cop::Rails::Date
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Rails::Date
- Extended by:
- AutoCorrector
- Includes:
- ConfigurableEnforcedStyle
- Defined in:
- lib/rubocop/cop/rails/date.rb
Overview
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 you can set a warning for ‘to_time` with `AllowToTime: false`. `AllowToTime` is `true` by default to prevent false positive on `DateTime` object.
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.'
- RESTRICT_ON_SEND =
%i[to_time to_time_in_current_zone].freeze
- 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
- #on_const(node) ⇒ Object
- #on_send(node) ⇒ Object (also: #on_csend)
Instance Method Details
#on_const(node) ⇒ Object
73 74 75 76 77 78 79 |
# File 'lib/rubocop/cop/rails/date.rb', line 73 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
81 82 83 84 85 86 87 88 89 |
# File 'lib/rubocop/cop/rails/date.rb', line 81 def on_send(node) return unless node.receiver && bad_methods.include?(node.method_name) return if allow_to_time? && node.method?(:to_time) return if safe_chain?(node) || safe_to_time?(node) check_deprecated_methods(node) add_offense(node.loc.selector, message: format(MSG_SEND, method: node.method_name)) end |