From f0b6f423213e3b84e1f621a68187a494978d7626 Mon Sep 17 00:00:00 2001 From: Daniel Vandersluis Date: Mon, 4 Nov 2024 13:59:05 -0500 Subject: [PATCH] Extend `Node#const_name` to `casgn` nodes. --- ...ew_extend_nodeconst_name_to_casgn_nodes.md | 1 + lib/rubocop/ast/node.rb | 7 +-- spec/rubocop/ast/node_spec.rb | 62 +++++++++++++++++++ 3 files changed, 66 insertions(+), 4 deletions(-) create mode 100644 changelog/new_extend_nodeconst_name_to_casgn_nodes.md diff --git a/changelog/new_extend_nodeconst_name_to_casgn_nodes.md b/changelog/new_extend_nodeconst_name_to_casgn_nodes.md new file mode 100644 index 000000000..fd510e835 --- /dev/null +++ b/changelog/new_extend_nodeconst_name_to_casgn_nodes.md @@ -0,0 +1 @@ +* [#330](https://github.com/rubocop/rubocop-ast/pull/330): Extend `Node#const_name` to `casgn` nodes. ([@dvandersluis][]) diff --git a/lib/rubocop/ast/node.rb b/lib/rubocop/ast/node.rb index dae3ac078..619b4bbf7 100644 --- a/lib/rubocop/ast/node.rb +++ b/lib/rubocop/ast/node.rb @@ -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 diff --git a/spec/rubocop/ast/node_spec.rb b/spec/rubocop/ast/node_spec.rb index 2b7d43b12..9d6845138 100644 --- a/spec/rubocop/ast/node_spec.rb +++ b/spec/rubocop/ast/node_spec.rb @@ -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