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

Style/RedundantBegin should be marked as unsafe for auto-correction #9681

Closed
gPrado opened this issue Apr 7, 2021 · 1 comment · Fixed by #9682
Closed

Style/RedundantBegin should be marked as unsafe for auto-correction #9681

gPrado opened this issue Apr 7, 2021 · 1 comment · Fixed by #9682
Labels

Comments

@gPrado
Copy link
Contributor

gPrado commented Apr 7, 2021

Style/RedundantBegin cop might auto-correct code incorrectly, leading to a performance issue or even a broken build. See example below:


Precondition

Given the following example class

class Test
  def initialize
    @first_run = false
  end

  def memoized
    @memoized ||= begin
      'memoized' if first_run
    end
  end

  def first_run
    # this might be an expensive operation
    fail 'already run!' if @first_run

    @first_run = true
  end
end

and the following test code:

test = Test.new
2.times { test.memoized }

Expected behavior

The code should not be auto-corrected, or maybe auto-corrected as the following:

class Test
  def initialize
    @first_run = false
  end

  def memoized
    @memoized ||= ('memoized' if first_run)
  end

  def first_run
    # this might be an expensive operation
    fail 'already run!' if @first_run

    @first_run = true
  end
end

Actual behavior

The code is auto-corrected as follows:

class Test
  def initialize
    @first_run = false
  end

  def memoized
    @memoized ||= 'memoized' if first_run
  end

  def first_run
    # this might be an expensive operation
    fail 'already run!' if @first_run

    @first_run = true
  end
end

which makes the test code raise an exception.

RuboCop version

1.12.1 (using Parser 3.0.1.0, rubocop-ast 1.4.1, running on ruby 2.6.6 x86_64-linux)

@koic
Copy link
Member

koic commented Apr 7, 2021

Thank you for the feedback. This is an auto-correction bug, so I opened #9682 that it will be safe auto-corrected code.

koic added a commit to koic/rubocop that referenced this issue Apr 7, 2021
…Begin`

Fixes rubocop#9681.

This PR fixes an incorrect auto-correct for `Style/RedundantBegin`
when using modifier `if` single statement in `begin` block.
bbatsov pushed a commit that referenced this issue Apr 8, 2021
Fixes #9681.

This PR fixes an incorrect auto-correct for `Style/RedundantBegin`
when using modifier `if` single statement in `begin` block.
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