Class: Rubycli::ConstantCapture

Inherits:
Object
  • Object
show all
Defined in:
lib/rubycli/constant_capture.rb

Overview

Observes constants defined while loading a file.

Instance Method Summary collapse

Constructor Details

#initializeConstantCapture

Returns a new instance of ConstantCapture.



8
9
10
11
# File 'lib/rubycli/constant_capture.rb', line 8

def initialize
  @captured = Hash.new { |hash, key| hash[key] = [] }
  @assignment_definitions = {}
end

Instance Method Details

#capture(file) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rubycli/constant_capture.rb', line 13

def capture(file)
  normalized_file = normalize(file)
  source = File.read(normalized_file)
  previous_names = @captured[normalized_file].dup
  previous_assignment_definitions = @assignment_definitions.fetch(normalized_file, {})
  executed_line_contexts = Hash.new { |hash, line| hash[line] = [] }
  assignment_events = Hash.new { |hash, line| hash[line] = [] }
  observed_events = []
  @captured[normalized_file] = []
  before_snapshot = constant_snapshot(normalized_file)
  trace = TracePoint.new(:class, :line, :call, :return, :b_call, :b_return, :c_call, :c_return) do |tp|
    location = tp.path
    next unless location && same_file?(normalized_file, location)

    observed_events << [tp.event, tp.self, tp.lineno, tp.method_id]
  end

  trace.enable
  yield
ensure
  trace&.disable
  if normalized_file && before_snapshot
    current_assignment_definitions = assigned_constant_definitions(source)
    apply_trace_events(
      observed_events,
      executed_line_contexts,
      assignment_events,
      normalized_file
    )
    after_snapshot = constant_snapshot(normalized_file)
    changed_names = after_snapshot.keys.select do |name|
      before_snapshot[name] != after_snapshot[name]
    end
    retained_names = previous_names.select do |name|
      previous_definitions = previous_assignment_definitions.fetch(name, [])
      current_definitions = current_assignment_definitions.fetch(name, [])
      definition_active = active_definition_retained?(
        previous_definitions,
        current_definitions,
        executed_line_contexts,
        assignment_events
      )
      after_snapshot.key?(name) && definition_active
    end
    @captured[normalized_file].concat(changed_names).concat(retained_names)
    @assignment_definitions[normalized_file] = current_assignment_definitions
  end
end

#constants_for(file) ⇒ Object



62
63
64
# File 'lib/rubycli/constant_capture.rb', line 62

def constants_for(file)
  Array(@captured[normalize(file)]).uniq
end