diff --git a/changelog/fix_format_string_token_nested_ignored_methods.md b/changelog/fix_format_string_token_nested_ignored_methods.md new file mode 100644 index 000000000000..f0a041b02378 --- /dev/null +++ b/changelog/fix_format_string_token_nested_ignored_methods.md @@ -0,0 +1 @@ +* [#10203](https://github.com/rubocop/rubocop/issues/10203): Fix `Style/FormatStringToken` to respect `IgnoredMethods` with nested structures. ([@tejasbubane][]) diff --git a/lib/rubocop/cop/style/format_string_token.rb b/lib/rubocop/cop/style/format_string_token.rb index 1d1fce891794..5d2256ed6443 100644 --- a/lib/rubocop/cop/style/format_string_token.rb +++ b/lib/rubocop/cop/style/format_string_token.rb @@ -102,7 +102,8 @@ def format_string_token?(node) end def use_ignored_method?(node) - (parent = node.parent) && parent.send_type? && ignored_method?(parent.method_name) + send_parent = node.each_ancestor(:send).first + send_parent && ignored_method?(send_parent.method_name) end def unannotated_format?(node, detected_style) diff --git a/spec/rubocop/cop/style/format_string_token_spec.rb b/spec/rubocop/cop/style/format_string_token_spec.rb index 99ce2c7ffa1e..2e1fe1d036a5 100644 --- a/spec/rubocop/cop/style/format_string_token_spec.rb +++ b/spec/rubocop/cop/style/format_string_token_spec.rb @@ -261,6 +261,19 @@ redirect("%{foo}") RUBY end + + it 'does not register an offense for value in nested structure' do + expect_no_offenses(<<~RUBY) + redirect("%{foo}", bye: "%{foo}") + RUBY + end + + it 'registers an offense for different method call within ignored method' do + expect_offense(<<~RUBY) + redirect("%{foo}", bye: foo("%{foo}")) + ^^^^^^ Prefer annotated tokens (like `%s`) over template tokens (like `%{foo}`). + RUBY + end end context 'when `IgnoredMethods: []`' do