File: any_instance_method.rb

package info (click to toggle)
libmocha-ruby 0.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 944 kB
  • ctags: 1,384
  • sloc: ruby: 7,265; makefile: 4
file content (55 lines) | stat: -rw-r--r-- 1,560 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
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
require 'mocha/class_method'

module Mocha

  class AnyInstanceMethod < ClassMethod
  
    def unstub
      remove_new_method
      restore_original_method
      stubbee.any_instance.reset_mocha
    end
    
    def mock
      stubbee.any_instance.mocha
    end
   
    def hide_original_method
      if method_exists?(method)
        begin
          stubbee.class_eval("alias_method :#{hidden_method}, :#{method}", __FILE__, __LINE__)
        rescue NameError
          # deal with nasties like ActiveRecord::Associations::AssociationProxy
        end
      end
    end

    def define_new_method
      stubbee.class_eval("def #{method}(*args, &block); self.class.any_instance.mocha.method_missing(:#{method}, *args, &block); end", __FILE__, __LINE__)
    end

    def remove_new_method
      stubbee.class_eval("remove_method :#{method}", __FILE__, __LINE__)
    end

    def restore_original_method
      if method_exists?(hidden_method)
        begin
          stubbee.class_eval("alias_method :#{method}, :#{hidden_method}; remove_method :#{hidden_method}", __FILE__, __LINE__)
        rescue NameError
          # deal with nasties like ActiveRecord::Associations::AssociationProxy
        end
      end
    end

    def method_exists?(method)
      existing_methods = []
      existing_methods += stubbee.public_instance_methods(false)
      existing_methods += stubbee.protected_instance_methods(false)
      existing_methods += stubbee.private_instance_methods(false)
      existing_methods.any? { |m| m.to_s == method.to_s }
    end
    
  end
  
end