Skip to content

Commit

Permalink
[Fix rubocop#535] Fix an error for Rails/HasManyOrHasOneDependent
Browse files Browse the repository at this point in the history
Fixes rubocop#535.

This PR fixes an error for `Rails/HasManyOrHasOneDependent`
when using lambda argument and not specifying any options.
  • Loading branch information
koic committed Sep 9, 2021
1 parent 1d22b8a commit d739948
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#535](https://github.com/rubocop/rubocop-rails/issues/535): Fix an error for `Rails/HasManyOrHasOneDependent` when using lambda argument and not specifying any options. ([@koic][])

## 2.12.0 (2021-09-09)

### New features
Expand Down
6 changes: 4 additions & 2 deletions lib/rubocop/cop/rails/has_many_or_has_one_dependent.rb
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ def valid_options_in_with_options_block?(node)
end

def contain_valid_options_in_with_options_block?(node)
if with_options_block(node)
return true if valid_options?(with_options_block(node))
if (options = with_options_block(node))
return true if valid_options?(options)

return false unless node.parent

Expand All @@ -114,6 +114,8 @@ def contain_valid_options_in_with_options_block?(node)
end

def valid_options?(options)
return false if options.nil?

options = options.first.children.first.pairs if options.first.kwsplat_type?

return true unless options
Expand Down
9 changes: 9 additions & 0 deletions spec/rubocop/cop/rails/has_many_or_has_one_dependent_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ class Person < ApplicationRecord
RUBY
end

it 'registers an offense when using lambda argument and not specifying any options' do
expect_offense(<<~RUBY)
class User < ApplicationRecord
has_one :articles, -> { where(active: true) }
^^^^^^^ Specify a `:dependent` option.
end
RUBY
end

it 'does not register an offense when specifying `:dependent` strategy' do
expect_no_offenses(<<~RUBY)
class Person < ApplicationRecord
Expand Down

0 comments on commit d739948

Please sign in to comment.