Module: MethodLoggerHelper

Included in:
Backend
Defined in:
app/helpers/method_logger_helper.rb

Overview

Module housing a logging helper. Once extending a module or a class all method inputs and outputs will be automatically logged.

Class Method Summary collapse

Class Method Details

.extended(base) ⇒ Object

Extends private and public methods of the target module/class with logging facilities. Inputs and outputs will be automatically logged when running with DEBUG log level.


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
# File 'app/helpers/method_logger_helper.rb', line 9

def self.extended(base)
  # Load instance methods directly from the given class
  methods = base.instance_methods(false) + base.private_instance_methods(false)

  # If this is used in Backend, we have to manually include methods from BackendApi
  # since they are in separate modules
  api_ancestors = base.ancestors.select { |anc| anc.to_s.start_with?('BackendApi') }
  api_ancestors.each { |anc| methods << anc.instance_methods(false) }

  # All methods are equal
  methods.flatten!

  # Do some magic and define proxy methods on-the-fly
  accessors = base.attr_accessors + base.attr_readers + base.attr_writers
  base.class_eval do
    methods.each do |method_name|
      next if accessors.include? method_name
      original_method = instance_method(method_name)

      define_method(method_name) do |*args, &block|
        Rails.logger.debug "---> #{base}##{method_name}(#{args.inspect})"
        return_value = original_method.bind(self).call(*args, &block)
        Rails.logger.debug "<--- #{base}##{method_name} #=> #{return_value.inspect}"
        return_value
      end
    end
  end
end