Class: RuboCop::Cop::Style::Iso8601Date

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/style/iso8601_date.rb

Overview

Flags use of strftime(ā€˜%Y-%m-%dā€™) for formatting dates the preferred method is using .iso8601

See also:

Examples:

# bad
DateTime.now.strftime('%Y-%m-%d')
Time.now.strftime("%Y-%m-%d")
Date.today.strftime("%Y-%m-%d")

# good
DateTime.now.to_date.iso8601
Time.now.to_date.iso8601
Date.today.iso8601

Constant Summary collapse

MSG =
'Use `iso8601` instead of `strftime("%Y-%m-%d")`.'
RESTRICT_ON_SEND =
[:strftime].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/rubocop/cop/style/iso8601_date.rb', line 34

def on_send(node)
  return unless strftime_iso8601?(node)

  range = range_between(node.loc.selector.begin_pos, node.loc.end.end_pos)

  add_offense(range) do |corrector|
    corrector.replace(range, 'to_date.iso8601')
  end
end

#strftime_iso8601?(node) ⇒ Object



30
31
32
# File 'lib/rubocop/cop/style/iso8601_date.rb', line 30

def_node_matcher :strftime_iso8601?, <<~PATTERN
(send $(...) :strftime (str "%Y-%m-%d"))
PATTERN