Skip to content

Commit

Permalink
[Fix #10557] Fix a false positive for Style/FetchEnvVar
Browse files Browse the repository at this point in the history
Fixes #10557.

This PR fixes a false positive for `Style/FetchEnvVar`
when `ENV['key']` is a receiver of `||=`.
  • Loading branch information
koic authored and bbatsov committed Apr 21, 2022
1 parent 16c6f74 commit 269fc46
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
1 change: 1 addition & 0 deletions changelog/fix_a_false_positive_for_style_fetch_env_var.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#10557](https://github.com/rubocop/rubocop/issues/10557): Fix a false positive for `Style/FetchEnvVar` when `ENV['key']` is a receiver of `||=`. ([@koic][])
11 changes: 7 additions & 4 deletions lib/rubocop/cop/style/fetch_env_var.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,14 @@ def message_chained_with_dot?(node)
node.parent.send_type? && node.parent.children.first == node && node.parent.dot?
end

# Allow if used as a flag (e.g., `if ENV['X']` or `!ENV['X']`) because
# it simply checks whether the variable is set.
# Also allow if receiving a message with dot syntax, e.g. `ENV['X'].nil?`.
# The following are allowed cases:
#
# - Used as a flag (e.g., `if ENV['X']` or `!ENV['X']`) because
# it simply checks whether the variable is set.
# - Receiving a message with dot syntax, e.g. `ENV['X'].nil?`.
# - `ENV['key']` is a receiver of `||=`, e.g. `ENV['X'] ||= y`.
def allowable_use?(node)
used_as_flag?(node) || message_chained_with_dot?(node)
used_as_flag?(node) || message_chained_with_dot?(node) || node.parent&.or_asgn_type?
end
end
end
Expand Down
8 changes: 8 additions & 0 deletions spec/rubocop/cop/style/fetch_env_var_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,14 @@
end
end

context 'when the node is a receiver of `||=`' do
it 'does not register an offense with `||`' do
expect_no_offenses(<<~RUBY)
ENV['X'] ||= y
RUBY
end
end

context 'when it is an argument of a method' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Expand Down

0 comments on commit 269fc46

Please sign in to comment.