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

Fix exception on Lint/InheritException when class definition has non-constant siblings #11930

Merged
merged 1 commit into from
Jun 5, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/fix_error_for_lint_exception.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11930](https://github.com/rubocop/rubocop/pull/11930): Fix exception on `Lint/InheritException` when class definition has non-constant siblings. ([@rafaelfranca][])
4 changes: 3 additions & 1 deletion lib/rubocop/cop/lint/inherit_exception.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,9 @@ def exception_class?(class_node)
def inherit_exception_class_with_omitted_namespace?(class_node)
return false if class_node.parent_class.namespace&.cbase_type?

class_node.left_siblings.any? { |sibling| exception_class?(sibling.identifier) }
class_node.left_siblings.any? do |sibling|
sibling.respond_to?(:identifier) && exception_class?(sibling.identifier)
end
end

def preferred_base_class
Expand Down
23 changes: 23 additions & 0 deletions spec/rubocop/cop/lint/inherit_exception_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,29 @@ class Exception < RuntimeError; end
end
end

context 'when inheriting `Exception` and has non-constant siblings' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
module Foo
include Bar

class C < Exception; end # This `Exception` is the same as `::Exception`.
^^^^^^^^^ Inherit from `RuntimeError` instead of `Exception`.
class Exception < RuntimeError; end
end
RUBY

expect_correction(<<~RUBY)
module Foo
include Bar

class C < RuntimeError; end # This `Exception` is the same as `::Exception`.
class Exception < RuntimeError; end
end
RUBY
end
end

context 'when inheriting `::Exception`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
Expand Down