Module: Ext::MethodHooker::ClassMethods

Defined in:
lib/ccb/ext/method_hooker.rb

Instance Method Summary collapse

Instance Method Details

#before_class_method(&block) ⇒ Object



59
60
61
# File 'lib/ccb/ext/method_hooker.rb', line 59

def before_class_method &block
  before_each_method :class, &block
end

#before_each_method(type, &block) ⇒ Object



12
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
53
54
55
56
57
# File 'lib/ccb/ext/method_hooker.rb', line 12

def before_each_method type, &block
  singleton = class << self; self; end
  case type
    when :instance
      this = self
      singleton.instance_eval do
        define_method :method_added do |name|
          last = instance_variable_get(:@__last_methods_added)
          return if last and last.include?(name)
          with = :"#{name}_with_before_each_method"
          without = :"#{name}_without_before_each_method"
          instance_variable_set(:@__last_methods_added, [name, with, without])
          this.class_eval do
            define_method with do |*args, &blk|
              instance_exec(name, args, blk, &block)
              send without, *args, &blk
            end
            alias_method without, name
            alias_method name, with
          end
          instance_variable_set(:@__last_methods_added, nil)
        end
      end
    when :class
      this = self
      singleton.instance_eval do
        define_method :singleton_method_added do |name|
          return if name == :singleton_method_added
          last = instance_variable_get(:@__last_singleton_methods_added)
          return if last and last.include?(name)
          with = :"#{name}_with_before_each_method"
          without = :"#{name}_without_before_each_method"
          instance_variable_set(:@__last_singleton_methods_added, [name, with, without])
          singleton.class_eval do
            define_method with do |*args, &blk|
              instance_exec(name, args, blk, &block)
              send without, *args, &blk
            end
            alias_method without, name
            alias_method name, with
          end
          instance_variable_set(:@__last_singleton_methods_added, nil)
        end
      end
  end
end

#before_instance_method(&block) ⇒ Object



63
64
65
# File 'lib/ccb/ext/method_hooker.rb', line 63

def before_instance_method &block
  before_each_method :instance, &block
end