diff --git a/changelog/fix_make_style_select_by_regexp_aware_of_env_const.md b/changelog/fix_make_style_select_by_regexp_aware_of_env_const.md new file mode 100644 index 00000000000..1db413e77ed --- /dev/null +++ b/changelog/fix_make_style_select_by_regexp_aware_of_env_const.md @@ -0,0 +1 @@ +* [#10457](https://github.com/rubocop/rubocop/pull/10457): Make `Style/SelectByRegexp` aware of `ENV` const. ([@koic][]) diff --git a/lib/rubocop/cop/style/select_by_regexp.rb b/lib/rubocop/cop/style/select_by_regexp.rb index b5d9c9c54eb..8d624b05550 100644 --- a/lib/rubocop/cop/style/select_by_regexp.rb +++ b/lib/rubocop/cop/style/select_by_regexp.rb @@ -69,6 +69,11 @@ class SelectByRegexp < Base } PATTERN + # @!method env_const?(node) + def_node_matcher :env_const?, <<~PATTERN + (const {nil? cbase} :ENV) + PATTERN + # @!method calls_lvar?(node, name) def_node_matcher :calls_lvar?, <<~PATTERN { @@ -94,7 +99,7 @@ def on_send(node) def receiver_allowed?(node) return false unless node - node.hash_type? || creates_hash?(node) + node.hash_type? || creates_hash?(node) || env_const?(node) end def register_offense(node, block_node, regexp) diff --git a/spec/rubocop/cop/style/select_by_regexp_spec.rb b/spec/rubocop/cop/style/select_by_regexp_spec.rb index 4bbbb77f976..96360aedb55 100644 --- a/spec/rubocop/cop/style/select_by_regexp_spec.rb +++ b/spec/rubocop/cop/style/select_by_regexp_spec.rb @@ -249,6 +249,13 @@ RUBY end + it 'does not register an offense when the receiver is `ENV`' do + expect_no_offenses(<<~RUBY) + ENV.#{method} { |x| x.match? /regexp/ } + ::ENV.#{method} { |x| x.match? /regexp/ } + RUBY + end + context 'with `numblock`s', :ruby27 do it 'registers an offense and corrects for `match?`' do expect_offense(<<~RUBY, method: method)