Module: MethodLogging

Defined in:
lib/method_logging.rb

Class Method Summary collapse

Class Method Details

.add(klass) ⇒ Object



3
4
5
6
7
8
9
# File 'lib/method_logging.rb', line 3

def add(klass)
  klass::LogMethods.each do |method|;
    unless klass.instance_methods.include?("#{method}_without_logging")
      add_method(klass, method)
    end
  end
end

.add_method(klass, method) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/method_logging.rb', line 11

def add_method(klass, method)
  klass.send :alias_method, :"#{method}_without_logging", method
  klass.class_eval <<-END
    def #{method}_with_logging(*args)
      MethodLogging.log("Called #{Time.now}: #{method}(\#{MethodLogging.strify(*args)})")
      #{method}_without_logging(*args)
    end
  END
  klass.send :alias_method, method, :"#{method}_with_logging"
end

.log(string) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/method_logging.rb', line 22

def log(string)
  path = Class.constants.include?('RAILS_ROOT') ? RAILS_ROOT : File.expand_path(File.dirname(__FILE__) + '/..')
  FileUtils.mkdir_p("#{path}/log") if File.exists?("#{path}/log")
  File.open("#{path}/log/method.log", 'a') do |f|
    f.puts string
  end
end

.strify(*args) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/method_logging.rb', line 30

def strify(*args)
  args.map do |arg|
    case arg.class.to_s
    when "String"
      %Q{"#{arg}"}
    when "Fixnum", "Integer", "Float"
      '%.5f' % arg.to_s
    when "Hash", "BSON::OrderedHash", "HashWithIndifferentAccess"
      string = arg.keys.sort.map do |k|
        "#{strify(k)} => #{strify(arg[k])}"
      end.join(', ')
      "{#{string}}"
    when "Array"
      string = arg.map do |v|
        string(v)
      end.join(', ')
      "[#{string}]"
    else
      "(#{arg.class} - #{arg})"
    end
  end.join(', ')
end