Class: Module

Inherits:
Object
  • Object
show all
Includes:
ZenTestMapping
Defined in:
lib/spy_on.rb

Instance Method Summary collapse

Instance Method Details

#call_site(depth = 1) ⇒ Object



25
26
27
28
29
# File 'lib/spy_on.rb', line 25

def call_site(depth=1)
  paths = caller(2).map { |path| path =~ /\(eval\)/ ? path : File.expand_path(path).sub(/#{File.expand_path Dir.pwd}/, '.') }
  our = paths.reject { |path| path =~ /vendor.rails|rubygems/ }
  return ["#{our.first} via "] + paths.first(depth)
end


31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/spy_on.rb', line 31

def print_tally(tallies)
  tallies.sort.each do |msg, tally|
    puts
    puts msg
    puts
    total = 0
    tally.values.each do |n| total += n; end
    puts "%5d: %s" % [total, "total"]

    tally.sort_by { |caller, count| -count }.first(5).each do |caller, count|
      puts "%5d: %s" % [count, caller.join("\n       ")]
    end
  end
end

#spy(msg, old_msg = nil, depth = 1) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/spy_on.rb', line 46

def spy msg, old_msg = nil, depth = 1
  puts "Spying on #{self}##{msg}"
  old_msg ||= "old_#{normal_to_test(msg.to_s).sub(/^test_/, '')}"
  alias_method old_msg, msg

  class_eval "
    @@tally_done = false
    @@tally ||= Hash.new { |h,k| h.safe_asgn(k, Hash.new(0)) }
    at_exit { at_exit { @@tally_done = true; print_tally @@tally if @@tally; @@tally = nil } }
    def #{msg}(*args, &block)
      unless @@tally_done then
        site = self.class.call_site(#{depth})
        x = @@tally.safe_idx('#{self}.#{msg}')
        x.safe_asgn(site, x.safe_idx(site) + 1)
      end
      #{old_msg}(*args, &block)
    end "
end

#spy_cm(*args) ⇒ Object



65
66
67
# File 'lib/spy_on.rb', line 65

def spy_cm *args
  this_sucks.spy *args
end

#spy_on(*msgs) ⇒ Object



69
70
71
72
73
# File 'lib/spy_on.rb', line 69

def spy_on *msgs
  msgs.each do |msg|
    spy msg
  end
end

#spy_on_cm(*msgs) ⇒ Object



75
76
77
# File 'lib/spy_on.rb', line 75

def spy_on_cm *msgs
  this_sucks.spy_on *msgs
end

#this_sucksObject



79
80
81
# File 'lib/spy_on.rb', line 79

def this_sucks
  class << self; self; end
end