Class: RuboCop::Cop::Rails::FreezeTime

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

Overview

Identifies usages of `travel_to` with an argument of the current time and change them to use `freeze_time` instead.

Examples:

# bad
travel_to(Time.now)
travel_to(Time.new)
travel_to(DateTime.now)
travel_to(Time.current)
travel_to(Time.zone.now)
travel_to(Time.now.in_time_zone)
travel_to(Time.current.to_time)

# good
freeze_time

Constant Summary collapse

MSG =
'Use `freeze_time` instead of `travel_to`.'
NOW_METHODS =
%i[now new current].freeze
CONVERT_METHODS =
%i[to_time in_time_zone].freeze
RESTRICT_ON_SEND =
%i[travel_to].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/cop/rails/freeze_time.rb', line 45

def on_send(node)
  child_node, method_name, time_argument = *node.first_argument&.children
  return if time_argument || !child_node
  return unless current_time?(child_node, method_name) || current_time_with_convert?(child_node, method_name)

  add_offense(node) do |corrector|
    last_argument = node.last_argument
    freeze_time_method = last_argument.block_pass_type? ? "freeze_time(#{last_argument.source})" : 'freeze_time'
    corrector.replace(node, freeze_time_method)
  end
end

#time_now?(node) ⇒ Object



36
37
38
# File 'lib/rubocop/cop/rails/freeze_time.rb', line 36

def_node_matcher :time_now?, <<~PATTERN
  (const {nil? cbase} {:Time :DateTime})
PATTERN

#zoned_time_now?(node) ⇒ Object



41
42
43
# File 'lib/rubocop/cop/rails/freeze_time.rb', line 41

def_node_matcher :zoned_time_now?, <<~PATTERN
  (send (const {nil? cbase} :Time) :zone)
PATTERN