Class: Reek::AST::ObjectRefs

Inherits:
Object
  • Object
show all
Defined in:
lib/reek/ast/object_refs.rb

Overview

ObjectRefs is used in CodeContexts. It manages and counts the references out of a method to other objects and to ‘self`.

E.g. this code:

def foo(thing)
  bar.call_me
  bar.maybe(thing.wat)
end

would make “@refs” below look like this after the TreeWalker has done his job:

{
  :self=>[2, 3], # `bar.call_me` and `bar.maybe` count as refs to `self` in line 2 and 3
  :thing=>[3]    # `thing.wat` in `bar.maybe()` counts as one reference to `thing`
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeObjectRefs

Returns a new instance of ObjectRefs.



23
24
25
# File 'lib/reek/ast/object_refs.rb', line 23

def initialize
  @refs = Hash.new { |refs, name| refs[name] = [] }
end

Instance Attribute Details

#refsObject (readonly, private)

Returns the value of attribute refs.



58
59
60
# File 'lib/reek/ast/object_refs.rb', line 58

def refs
  @refs
end

Instance Method Details

E.g. for

{ foo: [2], self: [2,3], bar: [3,4] }

this would return

{ self: [2,3], bar: [3,4] }

Returns:

  • (Hash)

    The most popular references.



43
44
45
46
# File 'lib/reek/ast/object_refs.rb', line 43

def most_popular
  max = refs.values.map(&:size).max
  refs.select { |_name, refs| refs.size == max }
end

#record_reference(name:, line: nil) ⇒ Int|nil

Records the references a given method in a CodeContext has including ‘self` (see the example at the beginning of this file).

Parameters:

  • name (Symbol)

    The name of the object that the method references or ‘self`.

  • line (Int) (defaults to: nil)

    The line number where this reference occurs.

Returns:

  • (Int|nil)

    The line number that was added (which might be nil).



34
35
36
# File 'lib/reek/ast/object_refs.rb', line 34

def record_reference(name:, line: nil)
  refs[name] << line
end

#references_to(name) ⇒ Object



48
49
50
# File 'lib/reek/ast/object_refs.rb', line 48

def references_to(name)
  refs[name]
end

#self_is_max?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/reek/ast/object_refs.rb', line 52

def self_is_max?
  refs.empty? || most_popular.key?(:self)
end