Class: Methods::InstanceMethodOverrider

Inherits:
Object
  • Object
show all
Defined in:
lib/xray_method_tracer/methods/instance_method_overrider.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ InstanceMethodOverrider

Returns a new instance of InstanceMethodOverrider.



10
11
12
# File 'lib/xray_method_tracer/methods/instance_method_overrider.rb', line 10

def initialize(klass)
  @klass = klass
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



8
9
10
# File 'lib/xray_method_tracer/methods/instance_method_overrider.rb', line 8

def klass
  @klass
end

Instance Method Details

#override!(source_locations) ⇒ Object

rubocop:disable Metrics/MethodLength



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
# File 'lib/xray_method_tracer/methods/instance_method_overrider.rb', line 15

def override!(source_locations)
  target_method_names = MethodSelector.new(klass).select_method_names_by_source_location(source_locations)
  target_klass = klass

  Module.new do
    require_relative "../utils/segment"
    require_relative "../utils/service_observer"

    target_method_names.each do |method_name|
      define_method(method_name) do |*args, **kwargs, &block|
        begin
          segment = Utils::ServiceObserver.begin_subsegment(
            Utils::Segment.build_name("IM", target_klass.name, method_name)
          )
          segment.(:args, Utils::Segment.format_args(args))
          result = if kwargs.empty?
                     super(*args, &block)
                   else
                     segment.(:kwargs, kwargs)
                     super(*args, **kwargs, &block)
                   end
        rescue StandardError => e
          segment.add_exception(e)
          raise e
        ensure
          Utils::ServiceObserver.end_subsegment
        end
        result
      end
    end
  end
end