Skip to content

Commit

Permalink
Add Node#loc_is? for easier test of locations
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Dec 13, 2024
1 parent 1213746 commit 2de953e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/rubocop/ast/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,17 @@ def guard_clause?
node.match_guard_clause?
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

location.is?(str)
end

# @!method match_guard_clause?(node = self)
def_node_matcher :match_guard_clause?, <<~PATTERN
[${(send nil? {:raise :fail} ...) return break next} single_line?]
Expand Down
24 changes: 24 additions & 0 deletions spec/rubocop/ast/node_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1109,4 +1109,28 @@ class << expr
end
end
end

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

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

it 'returns true when loc matches argument' do
expect(node).to be_loc_is(:begin, ':')
end

it 'returns false when loc does not match argument' do
expect(node).not_to be_loc_is(:begin, '!')
end
end

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

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

0 comments on commit 2de953e

Please sign in to comment.