Skip to content

Commit

Permalink
Merge pull request rubocop#13254 from koic/enhance_autocorrect_for_na…
Browse files Browse the repository at this point in the history
…ming_inclusive_language

Enhance the autocorrect for `Naming/InclusiveLanguage`
  • Loading branch information
koic committed Sep 22, 2024
2 parents 29e462e + 7fcdd43 commit 51f29dc
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#13254](https://github.com/rubocop/rubocop/pull/13254): Enhance the autocorrect for `Naming/InclusiveLanguage` when a sole suggestion is set. ([@koic][])
15 changes: 12 additions & 3 deletions lib/rubocop/cop/naming/inclusive_language.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,9 @@ def add_offenses_for_token(token, word_locations)
add_offense(range, message: create_message(word)) do |corrector|
suggestions = find_flagged_term(word)['Suggestions']

next unless suggestions.is_a?(String)

corrector.replace(range, suggestions)
if (preferred_term = preferred_sole_term(suggestions))
corrector.replace(range, preferred_term)
end
end
end
end
Expand Down Expand Up @@ -157,6 +157,15 @@ def preprocess_flagged_terms
set_regexes(flagged_term_strings, allowed_strings)
end

def preferred_sole_term(suggestions)
case suggestions
when Array
suggestions.one? && preferred_sole_term(suggestions.first)
when String
suggestions
end
end

def extract_regexp(term, term_definition)
return term_definition['Regex'] if term_definition['Regex']
return /(?:\b|(?<=[\W_]))#{term}(?:\b|(?=[\W_]))/ if term_definition['WholeWord']
Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cop/naming/inclusive_language_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,25 @@ class Nodewhitelist
end
end

context 'flagged term with one suggestion in array' do
let(:cop_config) do
{ 'FlaggedTerms' => {
'whitelist' => { 'Suggestions' => %w[allowlist] }
} }
end

it 'includes both suggestions in the offense message' do
expect_offense(<<~RUBY)
whitelist = %w(user1 user2)
^^^^^^^^^ Consider replacing 'whitelist' with 'allowlist'.
RUBY

expect_correction(<<~RUBY)
allowlist = %w(user1 user2)
RUBY
end
end

context 'flagged term with two suggestions' do
let(:cop_config) do
{ 'FlaggedTerms' => {
Expand Down

0 comments on commit 51f29dc

Please sign in to comment.