Skip to content

Commit

Permalink
Accept bracketed arrays within 2d arrays containing subarrays with co…
Browse files Browse the repository at this point in the history
…mplex content for `Style/WordArray` cop
  • Loading branch information
fatkodima authored and bbatsov committed Dec 31, 2022
1 parent fc3fa91 commit 1dfcd19
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/fix_word_array_to_accept_2d_arrays.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#10194](https://github.com/rubocop/rubocop/issues/10194): Accept bracketed arrays within 2d arrays containing subarrays with complex content for `Style/WordArray` cop. ([@fatkodima][])
7 changes: 7 additions & 0 deletions lib/rubocop/cop/style/word_array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ class << self
def on_array(node)
if bracketed_array_of?(:str, node)
return if complex_content?(node.values)
return if within_2d_array_of_complex_content?(node)

check_bracketed_array(node, 'w')
elsif node.percent_literal?(:string)
Expand All @@ -62,6 +63,12 @@ def on_array(node)

private

def within_2d_array_of_complex_content?(node)
return false unless (parent = node.parent)

parent.array_type? && parent.values.any? { |subarray| complex_content?(subarray.values) }
end

def complex_content?(strings, complex_regex: word_regex)
strings.any? do |s|
next unless s.str_content
Expand Down
28 changes: 28 additions & 0 deletions spec/rubocop/cop/style/word_array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,34 @@
A = %w(one two)
RUBY
end

it 'registers an offense and corrects for array within 2d array' do
expect_offense(<<~RUBY)
[
['one', 'One'],
^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
['two', 'Two']
^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
]
RUBY

expect_correction(<<~RUBY)
[
%w(one One),
%w(two Two)
]
RUBY
end

it 'does not register an offense for array within 2d array containing subarrays with complex content' do
expect_no_offenses(<<~RUBY)
[
['one', 'One'],
['two', 'Two'],
['forty two', 'Forty Two']
]
RUBY
end
end

context 'when EnforcedStyle is array' do
Expand Down

0 comments on commit 1dfcd19

Please sign in to comment.