Module: DebugLogging::ClassNotifier

Defined in:
lib/debug_logging/class_notifier.rb

Instance Method Summary collapse

Instance Method Details

#notifies(*methods_to_notify) ⇒ Object



5
6
7
8
9
10
11
12
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
# File 'lib/debug_logging/class_notifier.rb', line 5

def notifies(*methods_to_notify)
  payload = methods_to_notify.last.is_a?(Hash) && methods_to_notify.pop || {}
  if methods_to_notify.first.is_a?(Array)
    methods_to_notify = methods_to_notify.shift
  else
    # logged :meth1, :meth2, :meth3 without options is valid too
  end
  methods_to_notify.each do |method_to_notify|
    # method name must be a symbol
    method_to_notify = method_to_notify.to_sym
    original_method = method(method_to_notify)
    config_proxy = nil
    (class << self; self; end).class_eval do
      define_method(method_to_notify) do |*args, &block|
        config_proxy = if (proxy = instance_variable_get(DebugLogging::Configuration.config_pointer('k', method_to_notify)))
                         proxy
                       else
                         proxy = if !payload.empty?
                                   Configuration.new(**debug_config.to_hash.merge(payload))
                                 else
                                   debug_config
                                 end
                         proxy.register(method_to_notify)
                         instance_variable_set(DebugLogging::Configuration.config_pointer('k', method_to_notify), proxy)
                         proxy
                       end
        ActiveSupport::Notifications.instrument(
          debug_event_name_to_s(method_to_notify: method_to_notify), { args: args }.merge(payload)
        ) do
          original_method.call(*args, &block)
        end
      end
    end

    ActiveSupport::Notifications.subscribe(/log/) do |*args|
      config_proxy&.log do
        DebugLogging::LogSubscriber.log_event(ActiveSupport::Notifications::Event.new(*args))
      end
    end
  end
end