Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accept bracketed arrays within 2d arrays containing subarrays with complex content for Style/WordArray cop #11334

Merged
merged 1 commit into from
Dec 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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