Class: Sus::Mock
- Inherits:
-
Object
- Object
- Sus::Mock
- Defined in:
- lib/sus/mock.rb
Instance Attribute Summary collapse
-
#target ⇒ Object
readonly
Returns the value of attribute target.
Instance Method Summary collapse
- #after(method, &hook) ⇒ Object
- #before(method, &hook) ⇒ Object
- #clear ⇒ Object
-
#initialize(target) ⇒ Mock
constructor
A new instance of Mock.
- #print(output) ⇒ Object
- #replace(method, &hook) ⇒ Object
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
#target ⇒ Object (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, **, &block| result = super(*arguments, **, &block) hook.call(result, *arguments, **, &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, **, &block| hook.call(*arguments, **, &block) if execution_context == Thread.current super(*arguments, **, &block) end return self end |
#clear ⇒ Object
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 |
#print(output) ⇒ Object
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, **, &block| if execution_context == Thread.current hook.call(*arguments, **, &block) else super(*arguments, **, &block) end end return self end |