Permalink
Browse files

Added Hook#unbind().

  • Loading branch information...
1 parent 7f1d546 commit e952020ba165b949441b028a563420de6008008d Kaoru Kobo committed Feb 10, 2011
Showing with 46 additions and 3 deletions.
  1. +26 −1 lib/rhook.rb
  2. +20 −2 spec/rhook_spec.rb
View
@@ -51,9 +51,12 @@ def bound_object
# @yieldreturn The result value. (Returned value of called method.)
# @return [Hook] Created hook.
def bind(name, opt = {}, &block)
+ name = name.to_sym
hook = Hook.new
hook.hook_proc = block
- (@hooks_map[name.to_sym] ||= []).unshift( hook )
+ hook.bound_info = [self, name]
+ array = (@hooks_map[name] ||= [])
+ array.unshift( hook )
RHook.registry.class_cached_flag_map.delete(name)
opt[:disable] or hook.enable()
if opt[:group]
@@ -98,6 +101,18 @@ def unbind_all
self
end
+ # @group Methods for hook-side(outside)
+ #
+ # Unbind the bound hook on {#bound_object}. (Not commonly used, use {RHook::Hook#unbind}.)
+ # @return [self]
+ def unbind(name, hook_object)
+ name = name.to_sym
+ array = @hooks_map[name] or return
+ array.delete(hook_object)
+ RHook.registry.class_cached_flag_map.delete(name)
+ self
+ end
+
# ========================================================================
# @endgroup
# ========================================================================
@@ -324,6 +339,8 @@ class Hook
# The hook procedure registered by {RHookService#bind}.
# @return [Proc]
attr_accessor :hook_proc
+ # @private
+ attr_accessor :bound_info
# @private
def call(inv)
@@ -354,6 +371,14 @@ def disable
@enabled = false
self
end
+
+ # Unbind this hook.
+ # @return [self]
+ def unbind
+ service, name = @bound_info
+ service.unbind(name, self)
+ self
+ end
end #/Hook
#
View
@@ -126,14 +126,18 @@ def self.hack_class_method
# ================================================================
- describe "Hook object (enable/disable)" do
+ describe "Hook object (enable/disable/unbind)" do
class Target
def enable_disable()
"disabled"
end
+
+ def unbind_test()
+ "unbound"
+ end
end #/Target
- example do
+ example "enable/disable" do
hook = Target._rhook.hack(:enable_disable) do |inv|
"enabled"
end
@@ -150,6 +154,20 @@ def enable_disable()
end
t.enable_disable.should == "disabled"
end
+
+ example "unbind" do
+ hook = Target._rhook.hack(:unbind_test) do |inv|
+ "bound"
+ end
+
+ t = Target.new
+ t.unbind_test.should == "bound"
+
+ hook.unbind
+
+ t = Target.new
+ t.unbind_test.should == "unbound"
+ end
end

0 comments on commit e952020

Please sign in to comment.