Class: Module

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

Instance Method Summary collapse

Instance Method Details

#method_added(meth) ⇒ Object



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

def method_added(meth)
  maybe_call_callback(meth, self)
end

#singleton_method_added(meth) ⇒ Object



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

def singleton_method_added(meth)
  context = class << self; self; end
  maybe_call_callback(meth, context)
end

#watch_methods(*watch_for, &blk) ⇒ Object



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
# File 'lib/watch_methods.rb', line 15

def watch_methods(*watch_for, &blk)
  class_methods = false
  once = false
  if watch_for.last.is_a? Hash
    opts = watch_for.pop
    class_methods = opts[:class_methods] || class_methods
    once = opts[:once] || once
  end

  context = class_methods ? (class << self; self; end) : self

  added_watcher = context.class_eval { @method_added_watcher ||= {} }

  watch_for.each do |f|
    key = case f
          when Regexp
            f
          when Symbol
            f.to_s
          when String
            f
          when Array
            f.each {|*sub_f| sub_f << opts if opts; watch_methods(*sub_f, &blk)}
            nil
          end


    if key
      added_watcher[key] = {:callback => blk, :once => once}
      if meth = context.instance_methods(false).find{|m| key.match(m.to_s)}
        call_callback(added_watcher, key, meth)
      end
    end
  end
end