Skip to content

Commit

Permalink
Merge pull request #1737 from JuanVqz/fix-false-positive-of-instance-…
Browse files Browse the repository at this point in the history
…variable-assumption-with-struct-initialize

Fix Instance Variable Assumption false positive
  • Loading branch information
mvz authored Oct 11, 2023
2 parents 6d35ab2 + 033f00a commit 07ea5e4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
16 changes: 8 additions & 8 deletions lib/reek/smell_detectors/instance_variable_assumption.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def self.contexts
# @return [Array<SmellWarning>]
#
def sniff
assumptions = (variables_from_context - variables_from_initialize).uniq
assumptions = (variables_from_context - variables_from_initializers).uniq

assumptions.map do |assumption|
build_smell_warning(assumption)
Expand All @@ -42,14 +42,14 @@ def build_smell_warning(assumption)
parameters: { assumption: assumption.to_s })
end

def variables_from_initialize
initialize_exp = method_expressions.detect do |method|
method.name == :initialize
end

return [] unless initialize_exp
def variables_from_initializers
variables_from_initialize.map do |method|
method.each_node(:ivasgn).map(&:name)
end.flatten
end

initialize_exp.each_node(:ivasgn).map(&:name)
def variables_from_initialize
method_expressions.select { |method| method.name == :initialize }
end

def variables_from_context
Expand Down
23 changes: 23 additions & 0 deletions spec/reek/smell_detectors/instance_variable_assumption_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,27 @@ def delta

expect(src).to reek_of(:InstanceVariableAssumption, context: 'Alfa::Charlie')
end

it 'does not report when the initialize is in a nested Struct class' do
src = <<-RUBY
class Foo
Bar = Struct.new(:status) do
def initialize(status)
super
p 'bar created'
end
end
def initialize
@foo = :foo
end
def foo?
@foo == :foo
end
end
RUBY

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

0 comments on commit 07ea5e4

Please sign in to comment.