Skip to content

Commit

Permalink
Merge pull request #11930 from rafaelfranca/rm-fix-Exception
Browse files Browse the repository at this point in the history
Fix exception on Lint/InheritException when class definition has non-constant siblings
  • Loading branch information
koic committed Jun 5, 2023
2 parents a796b10 + f8aa6e2 commit aa62ee6
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
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

0 comments on commit aa62ee6

Please sign in to comment.