Skip to content

Commit 225a8d5

Browse files
authored
Merge pull request #311 from rock-core/hook_disposable
feat: make hook definition methods return a disposable for de-registration
2 parents b8d47e6 + f2578f1 commit 225a8d5

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

lib/roby/hooks.rb

+12
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,21 @@ def self.included(base)
1919
module ClassMethods
2020
include ::Hooks::ClassMethods
2121

22+
def define_hook_writer(name)
23+
define_method name do |method = nil, &block|
24+
_hooks[name] << (method || block)
25+
item = _hooks[name].last
26+
Roby.disposable { _hooks[name].delete(item) }
27+
end
28+
end
29+
2230
def define_hooks(callback, scope: ->(c, s) { s unless c.proc? })
2331
super
2432
end
2533
end
34+
35+
module InstanceHooks
36+
include ::Hooks::InstanceHooks
37+
end
2638
end
2739
end

test/test_hooks.rb

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# frozen_string_literal: true
2+
3+
require "roby/test/self"
4+
5+
module Roby
6+
describe Hooks do
7+
it "registers a hook for the given event" do
8+
obj = klass.new
9+
mock = flexmock
10+
mock.should_receive(:called).once
11+
obj.on_test { mock.called }
12+
obj.run_hook :on_test
13+
end
14+
it "returns a disposable that deregister the hook" do
15+
obj = klass.new
16+
mock = flexmock
17+
mock.should_receive(:called).never
18+
obj.on_test { mock.called }.dispose
19+
obj.run_hook :on_test
20+
end
21+
22+
def klass
23+
@klass ||= Class.new do
24+
include Hooks
25+
include Hooks::InstanceHooks
26+
27+
define_hook :on_test
28+
end
29+
end
30+
end
31+
end

0 commit comments

Comments
 (0)