Skip to content

Commit

Permalink
repeated hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
p committed Apr 7, 2024
1 parent b99861d commit e8da708
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
23 changes: 21 additions & 2 deletions lib/datadog/di/hook.rb
Original file line number Diff line number Diff line change
@@ -1,23 +1,42 @@
require 'concurrent-ruby'

module Datadog
module DI
module Hook
module_function def hook_method(cls_name, meth_name)
cls = symbolize_class_name(cls_name)
id = next_id

cls.class_eval do
saved = instance_method(meth_name)

remove_method(meth_name)
define_method(meth_name) do |*args, **kwargs|
saved.bind(self).call(*args, **kwargs).tap do |rv|
yield rv: rv
if INSTRUMENTED[[cls_name, meth_name]] == id
saved.bind(self).call(*args, **kwargs).tap do |rv|
yield rv: rv
end
else
saved.bind(self).call(*args, **kwargs)
end
end
end

INSTRUMENTED[[cls_name, meth_name]] = id
end

private

INSTRUMENTED = Concurrent::Map.new
NEXT_MUTEX = Mutex.new

module_function def next_id
NEXT_MUTEX.synchronize do
@next_id ||= 0
@next_id += 1
end
end

module_function def symbolize_class_name(cls_name)
Object.const_get(cls_name)
end
Expand Down
17 changes: 17 additions & 0 deletions spec/datadog/di/hook_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,22 @@ def hook_test_method_with_kwarg(kwarg:)
observed_calls.first.should == {rv: 2}
end
end

context 'when hooked twice' do
it 'only invokes callback once' do
described_class.hook_method(:HookTestClass, :hook_test_method) do |payload|
observed_calls << payload
end

described_class.hook_method(:HookTestClass, :hook_test_method) do |payload|
observed_calls << payload
end

HookTestClass.new.hook_test_method.should == 42

observed_calls.length.should == 1
observed_calls.first.should == {rv: 42}
end
end
end
end

0 comments on commit e8da708

Please sign in to comment.