reek icon indicating copy to clipboard operation
reek copied to clipboard

False positive for ModuleInitialize

Open jimeh opened this issue 4 years ago • 1 comments

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

jimeh avatar Jan 10 '20 13:01 jimeh

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

Jwashton avatar Dec 05 '23 14:12 Jwashton