Class: WrapMethod

Inherits:
Monitor
  • Object
show all
Includes:
Singleton
Defined in:
lib/agent/wrap_method.rb

Constant Summary collapse

@@wrapped =
[]

Instance Method Summary collapse

Instance Method Details

#key(clazz, method) ⇒ Object



9
10
11
# File 'lib/agent/wrap_method.rb', line 9

def key(clazz, method)
  clazz.to_s + ":" + method.to_s
end

#wrap(clazz, methodName, &block) ⇒ Object



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
46
47
48
49
50
51
52
# File 'lib/agent/wrap_method.rb', line 13

def wrap(clazz, methodName, &block)
  methodKey = key(clazz, methodName)
  if @@wrapped.index(methodKey) != nil
    raise methodKey + " Previously wrapped"
  end
  synchronize do
    clazz.instance_methods.each do |inst_method|
      if inst_method == methodName
        # crack the class
        clazz.instance_eval do
          # rename the original method
          inst_method_sym = inst_method.to_sym
          renamed_inst_method_sym = ("insight_wrapped_" + inst_method).to_sym
          puts "Aliasing " + inst_method.to_s + " -> " + renamed_inst_method_sym.to_s + "\n"
          alias_method renamed_inst_method_sym, inst_method_sym
          insight_method_name = ("insight_wrapper_" + inst_method).to_sym

          # Define a new method which executes our code at the beginning
          # and end
          puts "Creating " + insight_method_name.to_s + "\n"
          define_method insight_method_name do |*args, &argblock|
            block.call(:enter, clazz, inst_method, *args)
            if renamed_inst_method_sym.is_a?(Symbol)
              val = send(renamed_inst_method_sym, *args, &argblock)
            else
              val = renamed_inst_method_sym.call(*args, &argblock)
            end
            block.call(:exit, clazz, inst_method, *args)
          end

          # Alias our method over the original one
          puts "Aliasing " + inst_method.to_s + " -> " + insight_method_name.to_s + "\n"            
          alias_method inst_method_sym, insight_method_name
        end
        @@wrapped << methodKey
        @@wrapped.sort
      end
    end
  end
end