Skip to content

Commit

Permalink
Fix Module Initialize when nesting classes
Browse files Browse the repository at this point in the history
Fixes #1505
  • Loading branch information
JuanVqz committed Oct 18, 2023
1 parent 79350d9 commit 476f9ec
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 8 deletions.
20 changes: 12 additions & 8 deletions lib/reek/smell_detectors/module_initialize.rb
Expand Up @@ -21,14 +21,18 @@ def self.contexts # :nodoc:
# @return [Array<SmellWarning>]
#
def sniff
context.defined_instance_methods.each do |node|
if node.name == :initialize
return smell_warning(
lines: [source_line],
message: 'has initialize method')
end
end
[]
return [] if does_not_have_initializer_method?

smell_warning(
lines: [source_line],
message: 'has initialize method')
end

private

# :reek:FeatureEnvy
def does_not_have_initializer_method?
context.exp.direct_children.none? { |child| child.type == :def && child.name == :initialize }
end
end
end
Expand Down
40 changes: 40 additions & 0 deletions spec/reek/smell_detectors/module_initialize_spec.rb
Expand Up @@ -86,4 +86,44 @@ def initialize; end

expect(src).not_to reek_of(:ModuleInitialize)
end

it 'reports nothing for a method named initialize in a class assigned to a let variable' do
src = <<-RUBY
module Alfa
RSpec.describe Bravo do
let(:klass) do
Class.new do
def initialize; end
end
end
end
end
RUBY

expect(src).not_to reek_of(:ModuleInitialize)
end

it 'reports nothing for a DSL-based' do
src = <<-RUBY
module Alfa
bravo Class.new do
def initialize; end
end
end
RUBY

expect(src).not_to reek_of(:ModuleInitialize)
end

it 'reports nothing for a method named initialize in a variable assignment' do
src = <<-RUBY
module Alfa
bravo = Class.new do
def initialize; end
end
end
RUBY

expect(src).not_to reek_of(:ModuleInitialize)
end
end

0 comments on commit 476f9ec

Please sign in to comment.