Skip to content

Unsafe autocorrection with Style/SingleLineMethods for a single line condition #14344

@jibai31

Description

@jibai31

When running the "safe" autocorrection for the rule Style/SingleLineMethods, it does some invalid corrections, if the single line includes an if like below:

def complete() self.state = 'completed' if incomplete? end

Expected behavior

I'm expecting the autocorrect to output the following:

def complete
  self.state = 'completed' if incomplete?
end

Actual behavior

But instead it outputs the following, that breaks the code:

if incomplete?
  def complete
    self.state = 'completed'
  end
end

Steps to reproduce the problem

Define the class below:

# app/models/task.rb
class Task
  def complete() self.state = 'completed' if incomplete? end
end

Then run:

bundle exec rubocop -a app/models/task.rb

RuboCop version

$ bundle exec rubocop -V
1.77.0 (using Parser 3.3.8.0, rubocop-ast 1.45.1, analyzing as Ruby 3.2, running on ruby 3.2.8) [arm64-darwin24]
  - rubocop-capybara 2.22.1
  - rubocop-factory_bot 2.27.1
  - rubocop-performance 1.25.0
  - rubocop-rails 2.32.0
  - rubocop-rspec 3.6.0
  - rubocop-rspec_rails 2.31.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions