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
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/rails_otel_context/activerecord_context.rb', line 46

def singleton_method_added(name)
  super

  # Internal aliases created below (and by ScopeNameTracking) re-trigger
  # this hook; wrapping them would route calls back through the wrapper
  # and break receiver dispatch.
  return if name.to_s.start_with?('__otel')

  # ScopeNameTracking's redefinition of a scope method also re-triggers
  # this hook. That method is already wrapped — wrapping it again would
  # add a useless closure hop and leak a __otel_cm_orig_* alias.
  return if @_otel_wrapped_scopes&.key?(name)

  @_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
  alias_name = :"__otel_cm_orig_#{name}"
  # Alias instead of capturing a bound Method so inherited class methods
  # keep self = the actual receiver (see ScopeNameTracking).
  singleton_class.alias_method(alias_name, name)

  define_singleton_method(name) do |*args, **kwargs, &blk|
    result = send(alias_name, *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