Skip to content

Commit

Permalink
[Fix rubocop#451] Make Rails/RelativeDateConstant aware of `yesterd…
Browse files Browse the repository at this point in the history
…ay` and `tomorrow` methods.
  • Loading branch information
koic committed Mar 25, 2021
1 parent 2a3b870 commit f524711
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
* [#440](https://github.com/rubocop/rubocop-rails/issues/440): This PR makes `Rails/TimeZone` aware of timezone specifier. ([@koic][])
* [#381](https://github.com/rubocop/rubocop-rails/pull/381): Update `IgnoredMethods` list for `Lint/NumberConversion` to allow Rails' duration methods. ([@dvandersluis][])
* [#444](https://github.com/rubocop/rubocop-rails/issues/444): Mark `Rails/Blank` as unsafe auto-correction. ([@koic][])
* [#451](https://github.com/rubocop/rubocop-rails/issues/451): Make `Rails/RelativeDateConstant` aware of `yesterday` and `tomorrow` methods. ([@koic][])

## 2.9.1 (2020-12-16)

Expand Down
2 changes: 1 addition & 1 deletion lib/rubocop/cop/rails/relative_date_constant.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class RelativeDateConstant < Base

MSG = 'Do not assign %<method_name>s to constants as it ' \
'will be evaluated only once.'
RELATIVE_METHODS = %i[since from_now after ago until before].freeze
RELATIVE_METHODS = %i[since from_now after ago until before yesterday tomorrow].freeze

def on_casgn(node)
return if node.children[2]&.block_type?
Expand Down
34 changes: 34 additions & 0 deletions spec/rubocop/cop/rails/relative_date_constant_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,40 @@ def self.expired_at
RUBY
end

it 'registers and corrects an offense when using `Date.yesterday`' do
expect_offense(<<~RUBY)
class SomeClass
RECENT_DATE = Date.yesterday
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not assign yesterday to constants as it will be evaluated only once.
end
RUBY

expect_correction(<<~RUBY)
class SomeClass
def self.recent_date
Date.yesterday
end
end
RUBY
end

it 'registers and corrects an offense when using `Time.zone.tomorrow`' do
expect_offense(<<~RUBY)
class SomeClass
FUTURE_DATE = Time.zone.tomorrow
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not assign tomorrow to constants as it will be evaluated only once.
end
RUBY

expect_correction(<<~RUBY)
class SomeClass
def self.future_date
Time.zone.tomorrow
end
end
RUBY
end

it 'registers and corrects an offense when a method is chained after a relative method' do
expect_offense(<<~RUBY)
class SomeClass
Expand Down

0 comments on commit f524711

Please sign in to comment.