Browse files

Make hook to be called just once, even if both on_method/hack and to(…

…) are applied.
  • Loading branch information...
1 parent b728362 commit 7546386626e96ded1e8f965ce3ac8a0f8af39605 Kaoru Kobo committed Dec 4, 2010
Showing with 35 additions and 1 deletion.
  1. +9 −0 lib/rhook.rb
  2. +26 −1 spec/rhook_minor_spec.rb
View
9 lib/rhook.rb
@@ -21,6 +21,8 @@ def self.registry
class RHookService
# @private
attr_reader :hooks_map
+ # @private
+ attr_accessor :last_name_call_method_done
# @private
def initialize(obj)
@@ -124,6 +126,11 @@ def to(opt = {})
# @private
def call_method(name, method_name, args, block, opt = {})
+ if @last_name_call_method_done == name
+ return @obj.__send__(method_name, *args, &block)
+ end
+ @last_name_call_method_done = name
+
hooks = concat_hooks([], name)
hooks.empty? and return @obj.__send__(method_name, *args, &block)
@@ -136,6 +143,8 @@ def call_method(name, method_name, args, block, opt = {})
inv.target_proc = @obj.method(method_name)
inv.hint = opt[:hint] || {}
inv.proceed()
+ ensure
+ @last_name_call_method_done = nil
end
# Wraps the code block to be hookable.
View
27 spec/rhook_minor_spec.rb
@@ -31,7 +31,7 @@ def order_target
# [bug] It calls the target method/procedure twice when no hooks are registered.
t.order_call
t.order_ary.should == ["orig"]
-
+
t._rhook.bind(:order_target) do |inv|
t.order_ary << "before_call"
inv.call
@@ -119,6 +119,31 @@ def on_method_test_non_existent
result = Target._rhook.on_method(:on_method_test_non_existent, :ifdef => true)
result.should == true
end
+
+ end
+
+ # ========================================================================
+ describe "is applied to the method (== 'hack'ed), and also it is called via _rhook.to(), " do
+ class Target
+ def both_on_method_and_to
+ _rhook.to.both_on_method_and_to_target
+ end
+
+ def both_on_method_and_to_target
+
+ end
+ end
+
+ example "even though, the hook should be just called once." do
+ m = mock
+ m.should_receive(:called).once
+
+ Target._rhook.hack(:both_on_method_and_to_target) { |inv|
+ m.called
+ inv.call
+ }
+ Target.new.both_on_method_and_to()
+ end
end
end
end

0 comments on commit 7546386

Please sign in to comment.