Skip to content

Commit

Permalink
Refactor ArrayNode#percent_literal?
Browse files Browse the repository at this point in the history
  • Loading branch information
dvandersluis authored and marcandre committed Dec 13, 2024
1 parent e4a84a4 commit 4529384
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/rubocop/ast/node/array_node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ module AST
# to all `array` nodes within RuboCop.
class ArrayNode < Node
PERCENT_LITERAL_TYPES = {
string: /^%[wW]/,
symbol: /^%[iI]/
string: /\A%[wW]/,
symbol: /\A%[iI]/
}.freeze
private_constant :PERCENT_LITERAL_TYPES

Expand Down Expand Up @@ -50,7 +50,7 @@ def square_brackets?
# @return [Boolean] whether the array is enclosed in percent brackets
def percent_literal?(type = nil)
if type
loc.begin && loc.begin.source =~ PERCENT_LITERAL_TYPES[type]
loc.begin&.source&.match?(PERCENT_LITERAL_TYPES.fetch(type))
else
loc.begin&.source&.start_with?('%')
end
Expand Down
1 change: 1 addition & 0 deletions lib/rubocop/ast/node/str_node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class StrNode < Node
:q => /\A%q/,
:Q => /\A%Q/
}.freeze
private_constant :PERCENT_LITERAL_TYPES

def single_quoted?
loc_is?(:begin, "'")
Expand Down
8 changes: 8 additions & 0 deletions spec/rubocop/ast/array_node_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@
it { is_expected.not_to be_percent_literal(:string) }
it { is_expected.to be_percent_literal(:symbol) }
end

context 'with an invalid type' do
let(:source) { '%i(foo bar)' }

it 'raises KeyError' do
expect { array_node.percent_literal?(:foo) }.to raise_error(KeyError, 'key not found: :foo')
end
end
end

describe '#bracketed?' do
Expand Down

0 comments on commit 4529384

Please sign in to comment.