Skip to content

Commit

Permalink
Fix an error for Rails/Delegate
Browse files Browse the repository at this point in the history
This PR fixes the following error for `Rails/Delegate` when delegation to a cbase namespaced constant.

```console
  1) RuboCop::Cop::Rails::Delegate detects delegation to a cbase namespaced constant
     Failure/Error: return node.source unless node.namespace

     NoMethodError:
       undefined method 'namespace' for an instance of RuboCop::AST::Node
     # ./lib/rubocop/cop/rails/delegate.rb:113:in 'RuboCop::Cop::Rails::Delegate#full_const_name'
     # ./lib/rubocop/cop/rails/delegate.rb:115:in 'RuboCop::Cop::Rails::Delegate#full_const_name'
     # ./lib/rubocop/cop/rails/delegate.rb:115:in 'RuboCop::Cop::Rails::Delegate#full_const_name'
```

Follow-up to #1438.

There is no changelog entry since this is a bug fix for the above PR that has not been released yet.
  • Loading branch information
koic committed Feb 15, 2025
1 parent 4d0e655 commit b47e104
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/rubocop/cop/rails/delegate.rb
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,12 @@ def build_delegation(node, receiver)
end

def full_const_name(node)
return node.source unless node.namespace
return unless node.const_type?
unless node.namespace
return node.absolute? ? "::#{node.source}" : node.source
end

"#{full_const_name(node.namespace)}::#{node.children.last}"
"#{full_const_name(node.namespace)}::#{node.short_name}"
end

def trivial_delegate?(def_node)
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/rails/delegate_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,19 @@ def foo
RUBY
end

it 'detects delegation to a cbase namespaced constant' do
expect_offense(<<~RUBY)
def foo
^^^ Use `delegate` to define delegations.
::SomeModule::CONST.foo
end
RUBY

expect_correction(<<~RUBY)
delegate :foo, to: :'::SomeModule::CONST'
RUBY
end

it 'detects delegation to an instance variable' do
expect_offense(<<~RUBY)
def foo
Expand Down

0 comments on commit b47e104

Please sign in to comment.