blob: 915fe71b5f75b6bfaf6468fb366c60c5b539185c (
plain)
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
56
57
58
59
60
61
62
|
require 'mocha/metaclass'
module Mocha
class ClassMethod
attr_reader :stubbee, :method
def initialize(stubbee, method)
@stubbee, @method = stubbee, method
end
def stub
hide_original_method
define_new_method
end
def unstub
remove_new_method
restore_original_method
stubbee.reset_mocha
end
def mock
stubbee.mocha
end
def hide_original_method
stubbee.__metaclass__.class_eval "alias_method :#{hidden_method}, :#{method}" if stubbee.__metaclass__.method_defined?(method)
end
def define_new_method
stubbee.__metaclass__.class_eval "def #{method}(*args, &block); mocha.method_missing(:#{method}, *args, &block); end"
end
def remove_new_method
stubbee.__metaclass__.class_eval "remove_method :#{method}"
end
def restore_original_method
stubbee.__metaclass__.class_eval "alias_method :#{method}, :#{hidden_method}; remove_method :#{hidden_method}" if stubbee.__metaclass__.method_defined?(hidden_method)
end
def hidden_method
method_name = method.to_s.gsub(/\W/) {|s| "_substituted_character_#{s[0]}_" }
"__stubba__#{method_name}__stubba__"
end
def eql?(other)
return false unless (other.class == self.class)
(stubbee == other.stubbee) and (method == other.method)
end
alias_method :==, :eql?
def to_s
"#{stubbee}.#{method}"
end
end
end
|