Class: Sus::Mock

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target) ⇒ Mock

Returns a new instance of Mock.



10
11
12
13
14
15
# File 'lib/sus/mock.rb', line 10

def initialize(target)
	@target = target
	@interceptor = Module.new
	
	@target.singleton_class.prepend(@interceptor)
end

Instance Attribute Details

#targetObject (readonly)

Returns the value of attribute target.



17
18
19
# File 'lib/sus/mock.rb', line 17

def target
  @target
end

Instance Method Details

#after(method, &hook) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/sus/mock.rb', line 54

def after(method, &hook)
	execution_context = Thread.current

	@interceptor.define_method(method) do |*arguments, **options, &block|
		result = super(*arguments, **options, &block)
		hook.call(result, *arguments, **options, &block) if execution_context == Thread.current
		return result
	end

	return self
end

#before(method, &hook) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/sus/mock.rb', line 43

def before(method, &hook)
	execution_context = Thread.current

	@interceptor.define_method(method) do |*arguments, **options, &block|
		hook.call(*arguments, **options, &block) if execution_context == Thread.current
		super(*arguments, **options, &block)
	end

	return self
end

#clearObject



23
24
25
26
27
# File 'lib/sus/mock.rb', line 23

def clear
	@interceptor.instance_methods.each do |method_name|
		@interceptor.remove_method(method_name)
	end
end


19
20
21
# File 'lib/sus/mock.rb', line 19

def print(output)
	output.write("mock ", :context, @target.inspect)
end

#replace(method, &hook) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/sus/mock.rb', line 29

def replace(method, &hook)
	execution_context = Thread.current

	@interceptor.define_method(method) do |*arguments, **options, &block|
		if execution_context == Thread.current
			hook.call(*arguments, **options, &block)
		else
			super(*arguments, **options, &block)
		end
	end
	
	return self
end