troessner / reek

Code smell detector for Ruby
https://github.com/troessner/reek
MIT License
4.02k stars 279 forks source link

False positive for ModuleInitialize #1505

Open jimeh opened 4 years ago

jimeh commented 4 years ago

I've come across two instances of a false positive ModuleInitialize warnings when using anonymous class definitions.

First the RSpec related one:

module Alfa
  RSpec.describe Bravo do
    let(:klass) do
      Class.new do
        def initialize; end
      end
    end
  end
end

And secondly a DSL-based one:

module Alfa
  bravo Class.new do
    def initialize; end
  end
end

The DSL variant is probably not very likely to be done in a real-world scenario, but technically the initialize method is not defined on the module that Reek warns about. The RSpec variant is something I've come across in the real world however.

If the anonymous class is assigned to a constant it does not fail however, which makes sense cause it's no longer an anonymous class:

module Alfa
  Bravo = Class.new do
    def initialize; end
  end
end

A slightly different variant of this was reported in #1137 and fixed in #1287, but it specifically requires the anonymous class definition to be within a method definition on the module. Hence both of these are not reported:

module Alfa
  def self.bravo
    Class.new do
      def initialize; end
    end
  end
end
module Alfa
  def bravo
    Class.new do
      def initialize; end
    end
  end
end
Jwashton commented 9 months ago

In a very similar case, I also get a false positive for this rule when defining a Data class with an initializer.

module Example
  Thing = Data.define(:value) do
    def initialize(value: 'some default')
      super(value:)
    end
  end
end