Skip to content

Commit

Permalink
Enable autocorrection for Style/DateTime.
Browse files Browse the repository at this point in the history
  • Loading branch information
dvandersluis committed Sep 24, 2020
1 parent 33ce5ac commit 5b6934f
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 4 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -6,6 +6,10 @@

* [#8774](https://github.com/rubocop-hq/rubocop/issues/8774): Fix a false positive for `Layout/ArrayAlignment` with parallel assignment. ([@dvandersluis][])

### Changes

* [#8738](https://github.com/rubocop-hq/rubocop/issues/8738): Add autocorrection to `Style/DateTime`. ([@dvandersluis][])

## 0.91.1 (2020-09-23)

### Bug fixes
Expand Down
3 changes: 2 additions & 1 deletion config/default.yml
Expand Up @@ -2863,7 +2863,8 @@ Style/DateTime:
StyleGuide: '#date--time'
Enabled: false
VersionAdded: '0.51'
VersionChanged: '0.59'
VersionChanged: '0.92'
SafeAutoCorrect: false
AllowCoercion: false

Style/DefWithParentheses:
Expand Down
4 changes: 2 additions & 2 deletions docs/modules/ROOT/pages/cops_style.adoc
Expand Up @@ -1879,9 +1879,9 @@ an offense is reported.

| Disabled
| Yes
| No
| Yes (Unsafe)
| 0.51
| 0.59
| 0.92
|===

This cop checks for consistent usage of the `DateTime` class over the
Expand Down
13 changes: 12 additions & 1 deletion lib/rubocop/cop/style/date_time.rb
Expand Up @@ -42,6 +42,8 @@ module Style
# # good
# something.to_time
class DateTime < Base
extend AutoCorrector

CLASS_MSG = 'Prefer Time over DateTime.'
COERCION_MSG = 'Do not use #to_datetime.'

Expand All @@ -63,14 +65,23 @@ def on_send(node)
return if historic_date?(node)

message = to_datetime?(node) ? COERCION_MSG : CLASS_MSG
add_offense(node, message: message)

add_offense(node, message: message) do |corrector|
autocorrect(corrector, node)
end
end

private

def disallow_coercion?
!cop_config['AllowCoercion']
end

def autocorrect(corrector, node)
return if to_datetime?(node)

corrector.replace(node.receiver.loc.name, 'Time')
end
end
end
end
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/style/date_time_spec.rb
Expand Up @@ -8,20 +8,32 @@
DateTime.now
^^^^^^^^^^^^ Prefer Time over DateTime.
RUBY

expect_correction(<<~RUBY)
Time.now
RUBY
end

it 'registers an offense when using ::DateTime for current time' do
expect_offense(<<~RUBY)
::DateTime.now
^^^^^^^^^^^^^^ Prefer Time over DateTime.
RUBY

expect_correction(<<~RUBY)
::Time.now
RUBY
end

it 'registers an offense when using DateTime for modern date' do
expect_offense(<<~RUBY)
DateTime.iso8601('2016-06-29')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer Time over DateTime.
RUBY

expect_correction(<<~RUBY)
Time.iso8601('2016-06-29')
RUBY
end

it 'does not register an offense when using Time for current time' do
Expand Down

0 comments on commit 5b6934f

Please sign in to comment.