Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsafe Style/IfUnlessModifier Autocorrection for Code Using defined? #11040

Closed
chadrschroeder opened this issue Oct 2, 2022 · 0 comments · Fixed by #11041
Closed

Unsafe Style/IfUnlessModifier Autocorrection for Code Using defined? #11040

chadrschroeder opened this issue Oct 2, 2022 · 0 comments · Fixed by #11041
Labels

Comments

@chadrschroeder
Copy link

chadrschroeder commented Oct 2, 2022

Say that I have code like:

# Original Code
unless defined?(value)
  value = 'default'
end

This is reported as a Style/IfUnlessModifier failure. If I autocorrect it, it changes to:

# Autocorrected Code
value = 'default' unless defined?(value)

If value isn't defined, the original code will set it to 'default' while the autocorrected code will set it to nil.

I usually try to avoid using defined? altogether. But the example above is similar to what I was seeing in some legacy code and I wanted to document it.

Often code like this can be rewritten to use ||=, as long a false value doesn't ever need to override the default. Or it could be rewritten to use an additional value_defined variable that is set before the assignment of value.

I'm not sure what an autocorrection could be for this situation. Maybe RuboCop shouldn't do anything here?

RuboCop version

$ [bundle exec] rubocop -V
1.36.0 (using Parser 3.1.2.1, rubocop-ast 1.21.0, running on ruby 3.0.3) [x86_64-darwin20]
  - rubocop-rails 2.16.1
@koic koic added the bug label Oct 2, 2022
koic added a commit to koic/rubocop that referenced this issue Feb 28, 2023
Fixes rubocop#11040.

This PR fixes a false positive for `Style/IfUnlessModifier`
when `defined?`'s argument value is undefined.
bbatsov pushed a commit that referenced this issue Feb 28, 2023
Fixes #11040.

This PR fixes a false positive for `Style/IfUnlessModifier`
when `defined?`'s argument value is undefined.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants