Skip to content
This repository has been archived by the owner on Nov 3, 2021. It is now read-only.

Commit

Permalink
Added Hook#unbind().
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaoru Kobo committed Feb 10, 2011
1 parent 7f1d546 commit e952020
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
27 changes: 26 additions & 1 deletion lib/rhook.rb
Expand Up @@ -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]
Expand Down Expand Up @@ -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
# ========================================================================
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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

#
Expand Down
22 changes: 20 additions & 2 deletions spec/rhook_spec.rb
Expand Up @@ -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
Expand All @@ -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


Expand Down

0 comments on commit e952020

Please sign in to comment.