Skip to content

Commit

Permalink
Merge pull request rubocop#12099 from koic/fix_an_incorrect_autocorre…
Browse files Browse the repository at this point in the history
…ct_for_style_alias

Fix an incorrect autocorrect for `Style/Alias`
  • Loading branch information
koic committed Aug 6, 2023
2 parents 55fd380 + e068bdd commit 56b4edf
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
1 change: 1 addition & 0 deletions changelog/fix_an_incorrect_for_style_alias.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12099](https://github.com/rubocop/rubocop/pull/12099): Fix an incorrect autocorrect for `Style/Alias` when `EncforcedStyle: prefer_alias_method` and using `alias` with interpolated symbol argument. ([@koic][])
15 changes: 8 additions & 7 deletions lib/rubocop/cop/style/alias.rb
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,7 @@ def correct_alias_method_to_alias(corrector, send_node)

def correct_alias_to_alias_method(corrector, node)
replacement =
'alias_method ' \
":#{identifier(node.new_identifier)}, " \
":#{identifier(node.old_identifier)}"
"alias_method #{identifier(node.new_identifier)}, #{identifier(node.old_identifier)}"

corrector.replace(node, replacement)
end
Expand All @@ -146,10 +144,13 @@ def correct_alias_with_symbol_args(corrector, node)
corrector.replace(node.old_identifier, node.old_identifier.source[1..])
end

# @!method identifier(node)
def_node_matcher :identifier, <<~PATTERN
(sym $_)
PATTERN
def identifier(node)
if node.sym_type?
":#{node.children.first}"
else
node.source
end
end
end
end
end
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/style/alias_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,17 @@
RUBY
end

it 'registers an offense for `alias` with interpolated symbol argument' do
expect_offense(<<~'RUBY')
alias :"string#{interpolation}" :symbol
^^^^^ Use `alias_method` instead of `alias`.
RUBY

expect_correction(<<~'RUBY')
alias_method :"string#{interpolation}", :symbol
RUBY
end

it 'does not register an offense for alias_method' do
expect_no_offenses('alias_method :ala, :bala')
end
Expand Down

0 comments on commit 56b4edf

Please sign in to comment.