Skip to content

Commit

Permalink
Add Node#loc? to determine if a node has a given location
Browse files Browse the repository at this point in the history
  • Loading branch information
dvandersluis authored and marcandre committed Jan 27, 2025
1 parent 5763d46 commit 85bfe84
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
1 change: 1 addition & 0 deletions changelog/new_add_nodeloc_to_determine_if_a_node_has_a.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#346](https://github.com/rubocop/rubocop-ast/pull/346): Add `Node#loc?` to determine if a node has a given location. ([@dvandersluis][])
15 changes: 10 additions & 5 deletions lib/rubocop/ast/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -538,15 +538,20 @@ def guard_clause?
node.match_guard_clause?
end

# Shortcut to safely check if a location is present
# @return [Boolean]
def loc?(which_loc)
return false unless loc.respond_to?(which_loc)

!loc.public_send(which_loc).nil?
end

# Shortcut to safely test a particular location, even if
# this location does not exist or is `nil`
def loc_is?(which_loc, str)
return false unless loc.respond_to?(which_loc)

location = loc.public_send(which_loc)
return false unless location
return false unless loc?(which_loc)

location.is?(str)
loc.public_send(which_loc).is?(str)
end

# @!method match_guard_clause?(node = self)
Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/ast/node_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1110,6 +1110,28 @@ class << expr
end
end

describe '#loc?' do
let(:src) { '%i[>> sym << sym2]' }

before(:all) { RSpec::Matchers.alias_matcher :have_loc, :be_loc }

context 'when loc exists' do
let(:src) { ':sym' }

it 'returns true when the location exists' do
expect(node).to have_loc(:begin)
end
end

it 'returns false when requested loc is `nil`' do
expect(node).not_to have_loc(:begin)
end

it 'returns false when requested loc does not exist' do
expect(node).not_to have_loc(:foo)
end
end

describe '#loc_is?' do
let(:src) { '%i[>> sym << sym2]' }

Expand Down

0 comments on commit 85bfe84

Please sign in to comment.