Skip to content

Commit

Permalink
Support auto-correction for Rails/ScopeArgs
Browse files Browse the repository at this point in the history
This PR supports auto-correction for `Rails/ScopeArgs`.
  • Loading branch information
koic committed Jul 24, 2021
1 parent 64f67c9 commit aedce71
Show file tree
Hide file tree
Showing 5 changed files with 14 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
1 change: 1 addition & 0 deletions config/default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions docs/modules/ROOT/pages/cops_rails.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion lib/rubocop/cop/rails/scope_args.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,18 @@ 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

def_node_matcher :scope?, '(send nil? :scope _ $send)'

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
Expand Down
6 changes: 5 additions & 1 deletion spec/rubocop/cop/rails/scope_args_spec.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down

0 comments on commit aedce71

Please sign in to comment.