Module: RailsOtelContext::ActiveRecordContext::ClassMethodScopeTracking

Defined in:
lib/rails_otel_context/activerecord_context.rb

Overview

Tracks class methods (def self.name) that return an AR::Relation so their name is captured as code.activerecord.scope, complementing ScopeNameTracking which only handles the scope macro. Uses singleton_method_added to intercept methods after definition and source_location to skip Rails/gem internals.

Instance Method Summary collapse

Instance Method Details

#singleton_method_added(name) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rails_otel_context/activerecord_context.rb', line 46

def singleton_method_added(name)
  super

  @_otel_wrapped_class_methods ||= {}
  return if @_otel_wrapped_class_methods[name]

  app_root = RailsOtelContext::ActiveRecordContext.app_root
  return unless app_root

  begin
    loc = method(name).source_location
  rescue NameError
    return
  end
  loc_path = File.expand_path(loc[0])
  return unless loc_path.start_with?(app_root)
  return if loc_path.include?('/gems/')

  # Mark before define_singleton_method to prevent re-entrancy for this name
  @_otel_wrapped_class_methods[name] = true
  name_str = name.to_s.freeze
  original = method(name)

  define_singleton_method(name) do |*args, **kwargs, &blk|
    result = original.call(*args, **kwargs, &blk)
    if defined?(::ActiveRecord::Relation) && result.is_a?(::ActiveRecord::Relation)
      result.instance_variable_set(:@_otel_scope_name, name_str)
    end
    result
  end
rescue StandardError
  nil
end