From a21f4a3b28e6aa43bc0e93ca17f963de91c60ba4 Mon Sep 17 00:00:00 2001 From: Josh Nichols Date: Fri, 29 Sep 2023 10:29:42 -0400 Subject: [PATCH] Use ::Struct to avoid collisions with cop namespace We were trying to add a custom cop called `Struct/RequiresTypedStructHelper`, but ran into a problem where we got an error like: ``` undefined method `new' for RuboCop::Cop::Struct:Module /Users/technicalpickles/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-rails-2.21.1/lib/rubocop/cop/mixin/index_method.rb:105:in `module:IndexMethod' /Users/technicalpickles/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-rails-2.21.1/lib/rubocop/cop/mixin/index_method.rb:6:in `module:Cop' /Users/technicalpickles/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-rails-2.21.1/lib/rubocop/cop/mixin/index_method.rb:4:in `module:RuboCop' /Users/technicalpickles/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-rails-2.21.1/lib/rubocop/cop/mixin/index_method.rb:3:in `top (required)' /Users/technicalpickles/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-rails-2.21.1/lib/rubocop/cop/rails_cops.rb:7:in `require_relative' /Users/technicalpickles/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-rails-2.21.1/lib/rubocop/cop/rails_cops.rb:7:in `top (required)' /Users/technicalpickles/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-rails-2.21.1/lib/rubocop-rails.rb:16:in `require_relative' ``` It turned out this module has method that were calling `Struct.new`, but Ruby constant lookup ended up using our `Rubocop::Cop::Struct`, instead of the actual `Struct` class. We were able to work around it by changing the constant name, but `Struct` is always going to be part of the stdlib so a possible name collision. --- lib/rubocop/cop/mixin/index_method.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/rubocop/cop/mixin/index_method.rb b/lib/rubocop/cop/mixin/index_method.rb index 23ba0daae5..529639c467 100644 --- a/lib/rubocop/cop/mixin/index_method.rb +++ b/lib/rubocop/cop/mixin/index_method.rb @@ -102,7 +102,7 @@ def execute_correction(corrector, node, correction) end # Internal helper class to hold match data - Captures = Struct.new( + Captures = ::Struct.new( :transformed_argname, :transforming_body_expr ) do @@ -112,7 +112,7 @@ def noop_transformation? end # Internal helper class to hold autocorrect data - Autocorrection = Struct.new(:match, :block_node, :leading, :trailing) do + Autocorrection = ::Struct.new(:match, :block_node, :leading, :trailing) do def self.from_each_with_object(node, match) new(match, node, 0, 0) end