diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cc2e87cf2..8e96438b1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### New features * [#521](https://github.com/rubocop/rubocop-rails/pull/521): Support auto-correction for `Rails/Output`. ([@koic][]) +* [#520](https://github.com/rubocop/rubocop-rails/pull/520): Support auto-correction for `Rails/ScopeArgs`. ([@koic][]) ## 2.11.3 (2021-07-11) diff --git a/config/default.yml b/config/default.yml index fc98a63970..ef2d73a119 100644 --- a/config/default.yml +++ b/config/default.yml @@ -714,6 +714,7 @@ Rails/ScopeArgs: Description: 'Checks the arguments of ActiveRecord scopes.' Enabled: true VersionAdded: '0.19' + VersionChanged: '2.12' Include: - app/models/**/*.rb diff --git a/docs/modules/ROOT/pages/cops_rails.adoc b/docs/modules/ROOT/pages/cops_rails.adoc index f4d7baab0d..9c43a53934 100644 --- a/docs/modules/ROOT/pages/cops_rails.adoc +++ b/docs/modules/ROOT/pages/cops_rails.adoc @@ -4300,9 +4300,9 @@ Service::Mailer::update | Enabled | Yes -| No +| Yes | 0.19 -| - +| 2.12 |=== This cop checks for scope calls where it was passed diff --git a/lib/rubocop/cop/rails/scope_args.rb b/lib/rubocop/cop/rails/scope_args.rb index 3b90061d3e..04e6095399 100644 --- a/lib/rubocop/cop/rails/scope_args.rb +++ b/lib/rubocop/cop/rails/scope_args.rb @@ -14,6 +14,8 @@ module Rails # # good # scope :something, -> { where(something: true) } class ScopeArgs < Base + extend AutoCorrector + MSG = 'Use `lambda`/`proc` instead of a plain method call.' RESTRICT_ON_SEND = %i[scope].freeze @@ -21,7 +23,9 @@ class ScopeArgs < Base def on_send(node) scope?(node) do |second_arg| - add_offense(second_arg) + add_offense(second_arg) do |corrector| + corrector.replace(second_arg, "-> { #{second_arg.source} }") + end end end end diff --git a/spec/rubocop/cop/rails/scope_args_spec.rb b/spec/rubocop/cop/rails/scope_args_spec.rb index aa6703438a..62f619aee4 100644 --- a/spec/rubocop/cop/rails/scope_args_spec.rb +++ b/spec/rubocop/cop/rails/scope_args_spec.rb @@ -1,11 +1,15 @@ # frozen_string_literal: true RSpec.describe RuboCop::Cop::Rails::ScopeArgs, :config do - it 'registers an offense a scope with a method arg' do + it 'registers and corrects an offense a scope with a method arg' do expect_offense(<<~RUBY) scope :active, where(active: true) ^^^^^^^^^^^^^^^^^^^ Use `lambda`/`proc` instead of a plain method call. RUBY + + expect_correction(<<~RUBY) + scope :active, -> { where(active: true) } + RUBY end it 'accepts a non send argument' do