Skip to content

Commit

Permalink
Merge pull request #1096 from koic/make_rails_time_zone_aware_of_stri…
Browse files Browse the repository at this point in the history
…ng_to_time

[Fix #1094] Make `Rails/TimeZone` aware of `String#to_time`
  • Loading branch information
koic authored Aug 30, 2023
2 parents 930b96a + 49560be commit 8e43737
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1094](https://github.com/rubocop/rubocop-rails/issues/1094): Make `Rails/TimeZone` aware of `String#to_time`. ([@koic][])
17 changes: 12 additions & 5 deletions lib/rubocop/cop/rails/time_zone.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ module Rails
# # bad
# Time.now
# Time.parse('2015-03-02T19:05:37')
# '2015-03-02T19:05:37'.to_time
#
# # good
# Time.current
Expand All @@ -44,19 +45,17 @@ class TimeZone < Base
extend AutoCorrector

MSG = 'Do not use `%<current>s` without zone. Use `%<prefer>s` instead.'

MSG_ACCEPTABLE = 'Do not use `%<current>s` without zone. Use one of %<prefer>s instead.'

MSG_LOCALTIME = 'Do not use `Time.localtime` without offset or zone.'
MSG_STRING_TO_TIME = 'Do not use `String#to_time` without zone. Use `Time.zone.parse` instead.'

GOOD_METHODS = %i[zone zone_default find_zone find_zone!].freeze

DANGEROUS_METHODS = %i[now local new parse at].freeze

ACCEPTED_METHODS = %i[in_time_zone utc getlocal xmlschema iso8601 jisx0301 rfc3339 httpdate to_i to_f].freeze

TIMEZONE_SPECIFIER = /([A-Za-z]|[+-]\d{2}:?\d{2})\z/.freeze

RESTRICT_ON_SEND = %i[to_time].freeze

def on_const(node)
mod, klass = *node
# we should only check core classes
Expand All @@ -66,6 +65,14 @@ def on_const(node)
check_time_node(klass, node.parent) if klass == :Time
end

def on_send(node)
return if !node.receiver&.str_type? || !node.method?(:to_time)

add_offense(node.loc.selector, message: MSG_STRING_TO_TIME) do |corrector|
autocorrect(corrector, node)
end
end

private

def autocorrect(corrector, node)
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/rails/time_zone_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,19 @@
end
end

it 'registers an offense for `String#to_time`' do
expect_offense(<<~RUBY)
"2012-03-02 16:05:37".to_time
^^^^^^^ Do not use `String#to_time` without zone. Use `Time.zone.parse` instead.
RUBY
end

it 'does not register an offense for `to_time` without receiver' do
expect_no_offenses(<<~RUBY)
to_time
RUBY
end

it 'registers an offense for Time.parse' do
expect_offense(<<~RUBY)
Time.parse("2012-03-02 16:05:37")
Expand Down

0 comments on commit 8e43737

Please sign in to comment.