Module: ReferenceTracking::Tracker

Defined in:
lib/reference_tracking/tracker.rb

Class Method Summary collapse

Class Method Details

.delegate_tracking(object, references, target, delegateds, method = :track_calls_on) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/reference_tracking/tracker.rb', line 43

def delegate_tracking(object, references, target, delegateds, method = :track_calls_on)
  tracker_for(object).send(:define_method, target) do |*args, &block|
    super(*args, &block).tap do |object|
      Array.wrap(delegateds).each do |delegated|
        delegated = [delegated] if delegated.is_a?(Hash)
        _method = delegated.to_s.start_with?('.') ? :track_calls_to : method
        Tracker.setup(object, references, delegated, :delegated => _method)
      end
    end
  end
end

.setup(object, references, targets, options = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/reference_tracking/tracker.rb', line 11

def setup(object, references, targets, options = {})
  Array.wrap(targets).each do |target|
    if target.is_a?(Hash)
      target.each { |target, nested| delegate_tracking(object, references, target, nested) }
    elsif options[:delegated]
      send(options[:delegated], object, references, target)
    elsif target.to_s.include?('.')
      delegate_tracking(object, references, *target.to_s.split('.') << :track_calls_to)
    else
      track_calls_on(object, references, target)
    end
  end
end

.track_calls_on(object, references, target) ⇒ Object



29
30
31
32
33
# File 'lib/reference_tracking/tracker.rb', line 29

def track_calls_on(object, references, target)
  tracker_for(object).send(:define_method, target) do |*args, &block|
    super(*args, &block).tap { |object| Array(object).each { |object| references << [object, nil] } }
  end
end

.track_calls_to(object, references, method) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/reference_tracking/tracker.rb', line 35

def track_calls_to(object, references, method)
  method = method.to_s.split('.').last if method.to_s.include?('.')
  tracker_for(object).send(:define_method, method) do |*args, &block|
    references << [self, method]
    super(*args, &block)
  end
end

.tracker_for(object) ⇒ Object



25
26
27
# File 'lib/reference_tracking/tracker.rb', line 25

def tracker_for(object)
  Module.new.tap { |tracker| object.singleton_class.send(:include, tracker) }
end