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

Support auto-correction for Rails/ScopeArgs #520

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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