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

Incorrect safe navigation autocorrection #5079

Closed
eugentorica opened this issue Nov 20, 2017 · 5 comments
Closed

Incorrect safe navigation autocorrection #5079

eugentorica opened this issue Nov 20, 2017 · 5 comments
Labels

Comments

@eugentorica
Copy link

if state && state.country_id != country_id
  errors.add(:state, "doesn't belong to the selected country.")
end

is automatically converted to

if state&.country_id != country_id
  errors.add(:state, "doesn't belong to the selected country.")
end

This is incorrect because state can be nil.
Expected behaviour: no changes required.

$ rubocop -V
Rubocop version: 0.51.0 (using Parser 2.4.0.2, running on ruby 2.4.1 x86_64-linux)

@asherkach
Copy link
Contributor

The safe navigation operator, introduced in ruby 2.3.0, evaluates the left hand side of state&.country_id to nil if state is nil. Thus, the autocorrection probably doesn't change behavior as you suggest.

That said, if state and country_id are both nil, then the former adds the error while the latter does not add the error. Is this your concern?

@minyoung
Copy link

The autocorrect also triggers when I have this code: if actions && actions.length > 0

Rubocop wants to rewrite it to: if actions&.length > 0

If actions is nil, then the rewrite will result in: nil > 0, which will generate an error...

$ rubocop -V
0.51.0 (using Parser 2.4.0.2, running on ruby 2.4.1 x86_64-linux)

@asherkach
Copy link
Contributor

Right. Presumably the cop should not rewrite if the result is being used in a comparison, it should only rewrite if the truthiness of falsiness of the result is being used?

@Drenmi
Copy link
Collaborator

Drenmi commented Nov 21, 2017

I can not reproduce this using the code provided. Please add the complete output using -D, and any relevant configuration. 🙂

@Drenmi
Copy link
Collaborator

Drenmi commented Nov 22, 2017

Was able to reproduce it now.

@Drenmi Drenmi added the bug label Nov 22, 2017
tiagotex added a commit to tiagotex/rubocop that referenced this issue Nov 23, 2017
`Style/SafeNavigation` returns false positives and tries to autocorrect when safe guarding a comparison on a chained method call.
bbatsov pushed a commit that referenced this issue Nov 24, 2017
`Style/SafeNavigation` returns false positives and tries to autocorrect when safe guarding a comparison on a chained method call.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants