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

Autocorrect for Style/CaseLikeIf changes behaviour of regex match data #8354

Closed
krauselukas opened this issue Jul 17, 2020 · 2 comments · Fixed by #8504
Closed

Autocorrect for Style/CaseLikeIf changes behaviour of regex match data #8354

krauselukas opened this issue Jul 17, 2020 · 2 comments · Fixed by #8504
Labels

Comments

@krauselukas
Copy link

krauselukas commented Jul 17, 2020

The rubocop auto-correct for the Style/CaseLikeIf cop had some unexpected behaviour when dealing with the ruby match operator in combination with if/elsif statements.
To be more precise, the match data object is not returned anymore after moving the regex condition to a case statement.


Expected behavior

The Style/CaseLikeIf cop takes the =~ match operator into account.

Actual behavior

The Style/CaseLikeIf cop autocorrect changed the behaviour of the code, which lead to faulty results and failing test's.

Steps to reproduce the problem

Before

params[:command] = 'set-disable'
if params[:command] == 'remove'
  # do something
elsif %r{^set-(?<status>disable|enable)$} =~ params[:command]
  puts status
end

Result
disable

After auto-correct

params[:command] = 'set-disable'
case params[:command]
when 'remove'
  # do something
when /^set-(?<status>disable|enable)$/
  puts status
end

Result
NameError (undefined local variable or method 'status' for main:Object)

See also openSUSE/open-build-service@6909ea7

RuboCop version

frontend@3099cfde322d:/obs/src/api> rubocop -V
0.88.0 (using Parser 2.7.1.4, rubocop-ast 0.1.0, running on ruby 2.5.8 x86_64-linux-gnu)
@dmytro-savochkin
Copy link

I think I can come up with something. Actually I wrote the code to fix this actual problem but also want to fix some other edge-cases. Will probably make a PR in a couple of weeks.

@marcandre
Copy link
Contributor

Indeed, this is because the only way to get local variables set this way is /literal_regex(?<named>)/ =~ var. If the regexp is stored in a variable or constant and used later with =~ that won't work, or if used with === like here it won't work either. 🤷‍♂️

dmytro-savochkin pushed a commit to dmytro-savochkin/rubocop that referenced this issue Oct 2, 2020
@koic koic closed this as completed in #8504 Oct 2, 2020
koic added a commit that referenced this issue Oct 2, 2020
[Fix #8354] Fix Style/CaseLikeIf to handle regexp named captures
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.

4 participants