Class: RuboCop::Cop::Sevencop::RailsDateAndTimeCalculation

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/sevencop/rails_date_and_time_calculation.rb

Overview

Prefer ActiveSupport date and time helper.

Examples:

# bad
Time.zone.now

# good
Time.current

# bad
Time.zone.today

# good
Date.current

# bad
Time.current.to_date

# good
Date.current

# bad
Date.current.tomorrow

# good
Date.tomorrow

# bad
Date.current.yesterday

# good
Date.yesterday

# bad
date == Date.current
Date.current == date

# good
date.today?

# bad
date == Date.tomorrow
Date.tomorrow == date

# good
date.tomorrow?

# bad
date == Date.yesterday
Date.yesterday == date

# good
date.yesterday?

# bad
Time.current - n.days
Time.zone.now - n.days

# good
n.days.ago

# bad
Time.current + n.days

# good
n.days.since

# bad
Date.current - 1
Date.current - 1.day

# good
Date.yesterday

# bad
Date.current + 1
Date.current + 1.day

# good
Date.tomorrow

# bad
time.after?(Time.current)
time > Time.current
Time.current < time
Time.current.before?(time)

# good
time.future?

# bad
time.before?(Time.current)
time < Time.current
Time.current > time
Time.current.after?(time)

# good
time.past?

Cop Safety Information:

  • This cop is unsafe because it considers that ‘n.days` is a Duration, and `date` in `date == Date.current` is a Date, but there is no guarantee.

Constant Summary collapse

CALCULATION_METHOD_NAMES =
%i[
  -
  +
].to_set.freeze
COMPARISON_METHOD_NAMES =
%i[
  <
  >
  after?
  before?
].to_set.freeze
DURATION_METHOD_NAMES =
%i[
  day
  days
  fortnight
  fortnights
  hour
  hours
  minute
  minutes
  month
  months
  second
  seconds
  week
  weeks
  year
  years
].to_set.freeze
MSG =
'Prefer ActiveSupport date and time helper.'
RESTRICT_ON_SEND =
[
  *CALCULATION_METHOD_NAMES,
  *COMPARISON_METHOD_NAMES,
  :==,
  :now,
  :to_date,
  :today,
  :tomorrow,
  :yesterday
].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ void

This method returns an undefined value.

Parameters:

  • node (RuboCop::AST::SendNode)


157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/rubocop/cop/sevencop/rails_date_and_time_calculation.rb', line 157

def on_send(node)
  case node.method_name
  when :-
    check_subtraction(node)
  when :+
    check_addition(node)
  when :==
    check_equality(node)
  when :<, :before?
    check_less_than(node)
  when :>, :after?
    check_greater_than(node)
  when :now
    check_now(node)
  when :to_date
    check_to_date(node)
  when :today
    check_today(node)
  when :tomorrow
    check_tomorrow(node)
  when :yesterday
    check_yesterday(node)
  end
end