Skip to content

Commit b47e104

Browse files
committed
Fix an error for Rails/Delegate
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.
1 parent 4d0e655 commit b47e104

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

lib/rubocop/cop/rails/delegate.rb

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,9 +110,12 @@ def build_delegation(node, receiver)
110110
end
111111

112112
def full_const_name(node)
113-
return node.source unless node.namespace
113+
return unless node.const_type?
114+
unless node.namespace
115+
return node.absolute? ? "::#{node.source}" : node.source
116+
end
114117

115-
"#{full_const_name(node.namespace)}::#{node.children.last}"
118+
"#{full_const_name(node.namespace)}::#{node.short_name}"
116119
end
117120

118121
def trivial_delegate?(def_node)

spec/rubocop/cop/rails/delegate_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,19 @@ def foo
280280
RUBY
281281
end
282282

283+
it 'detects delegation to a cbase namespaced constant' do
284+
expect_offense(<<~RUBY)
285+
def foo
286+
^^^ Use `delegate` to define delegations.
287+
::SomeModule::CONST.foo
288+
end
289+
RUBY
290+
291+
expect_correction(<<~RUBY)
292+
delegate :foo, to: :'::SomeModule::CONST'
293+
RUBY
294+
end
295+
283296
it 'detects delegation to an instance variable' do
284297
expect_offense(<<~RUBY)
285298
def foo

0 commit comments

Comments
 (0)