Skip to content

Commit

Permalink
Use ::Struct to avoid collisions with cop namespace
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
technicalpickles committed Sep 29, 2023
1 parent e1b1fff commit a21f4a3
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/rubocop/cop/mixin/index_method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit a21f4a3

Please sign in to comment.