Class: MethodLogger::Mixin

Inherits:
Module
  • Object
show all
Defined in:
lib/method_logger.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Mixin

Returns a new instance of Mixin.



6
7
8
9
# File 'lib/method_logger.rb', line 6

def initialize(options = {})
  @_options = default_options.merge(options)
  @_methods = options[:methods]
end

Instance Method Details

#included(base_class) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/method_logger.rb', line 11

def included(base_class)
  options = @_options
  methods = @_methods || base_class.instance_methods(options[:include_inherited])
  methods -= Object.methods if options[:include_inherited]
  methods += base_class.private_instance_methods(false)
  methods -= options[:ignored_methods]
  formatter = options.delete(:formatter) || default_formatter
  logger = options[:logger] || default_logger(options)

  base_class.class_eval do
    methods.each do |method_name|
      method = instance_method(method_name)

      define_method(method_name) do |*args, &block|
        return_value = method.bind(self).call(*args, &block)
        text = formatter.call(base_class, method_name, args.inspect, return_value.inspect)
        puts(text) if options[:log_to_stdout]
        logger.info(text) if options[:log_to_file]
        return_value
      end
    end
  end
end