Skip to content

Commit

Permalink
Extend Node#const_name to casgn nodes.
Browse files Browse the repository at this point in the history
  • Loading branch information
dvandersluis committed Nov 4, 2024
1 parent e466119 commit f0b6f42
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 4 deletions.
1 change: 1 addition & 0 deletions changelog/new_extend_nodeconst_name_to_casgn_nodes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#330](https://github.com/rubocop/rubocop-ast/pull/330): Extend `Node#const_name` to `casgn` nodes. ([@dvandersluis][])
7 changes: 3 additions & 4 deletions lib/rubocop/ast/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -312,13 +312,12 @@ def source_length
def_node_matcher :str_content, '(str $_)'

def const_name
return unless const_type?
return unless const_type? || casgn_type?

namespace, name = *self
if namespace && !namespace.cbase_type?
"#{namespace.const_name}::#{name}"
"#{namespace.const_name}::#{short_name}"
else
name.to_s
short_name.to_s
end
end

Expand Down
62 changes: 62 additions & 0 deletions spec/rubocop/ast/node_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -986,4 +986,66 @@ class << expr
end
end
end

describe '#const_name' do
context 'when given a `const` node' do
context 'FOO' do
let(:src) { 'FOO' }

it 'returns FOO' do
expect(node.const_name).to eq('FOO')
end
end

context 'FOO::BAR::BAZ' do
let(:src) { 'FOO::BAR::BAZ' }

it 'returns FOO::BAR::BAZ' do
expect(node.const_name).to eq('FOO::BAR::BAZ')
end
end

context '::FOO::BAR::BAZ' do
let(:src) { '::FOO::BAR::BAZ' }

it 'returns FOO::BAR::BAZ' do
expect(node.const_name).to eq('FOO::BAR::BAZ')
end
end
end

context 'when given a `casgn` node' do
context 'FOO = 1' do
let(:src) { 'FOO = 1' }

it 'returns FOO' do
expect(node.const_name).to eq('FOO')
end
end

context 'FOO::BAR::BAZ = 1' do
let(:src) { 'FOO::BAR::BAZ = 1' }

it 'returns FOO::BAR::BAZ' do
expect(node.const_name).to eq('FOO::BAR::BAZ')
end
end

context '::FOO::BAR::BAZ = 1' do
let(:src) { '::FOO::BAR::BAZ = 1' }

it 'returns FOO::BAR::BAZ' do
expect(node.const_name).to eq('FOO::BAR::BAZ')
end
end
end

context 'when given a `send` node' do
let(:src) { 'foo.bar' }

it 'return nil' do
expect(node.const_name).to be_nil
end
end
end
end

0 comments on commit f0b6f42

Please sign in to comment.