mirror of https://github.com/rails/rails
Merge pull request #40055 from composerinteralia/single-argument-callable-notification-listeners
Allow subscribing with a single argument callable
This commit is contained in:
commit
8435250167
|
@ -91,13 +91,13 @@ module ActiveSupport
|
|||
if listener.respond_to?(:start) && listener.respond_to?(:finish)
|
||||
subscriber_class = Evented
|
||||
else
|
||||
# Doing all this to detect a block like `proc { |x| }` vs
|
||||
# `proc { |*x| }` or `proc { |**x| }`
|
||||
if listener.respond_to?(:parameters)
|
||||
params = listener.parameters
|
||||
if params.length == 1 && params.first.first == :opt
|
||||
subscriber_class = EventObject
|
||||
end
|
||||
# Doing this to detect a single argument block or callable
|
||||
# like `proc { |x| }` vs `proc { |*x| }`, `proc { |**x| }`,
|
||||
# or `proc { |x, **y| }`
|
||||
procish = listener.respond_to?(:parameters) ? listener : listener.method(:call)
|
||||
|
||||
if procish.arity == 1 && procish.parameters.length == 1
|
||||
subscriber_class = EventObject
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -80,6 +80,32 @@ module Notifications
|
|||
ensure
|
||||
ActiveSupport::Notifications.notifier = old_notifier
|
||||
end
|
||||
|
||||
def test_subscribe_with_a_single_arity_lambda_listener
|
||||
event_name = nil
|
||||
listener = ->(event) do
|
||||
event_name = event.name
|
||||
end
|
||||
|
||||
@notifier.subscribe(&listener)
|
||||
ActiveSupport::Notifications.instrument("event_name")
|
||||
|
||||
assert_equal "event_name", event_name
|
||||
end
|
||||
|
||||
def test_subscribe_with_a_single_arity_callable_listener
|
||||
event_name = nil
|
||||
listener = Class.new do
|
||||
define_method :call do |event|
|
||||
event_name = event.name
|
||||
end
|
||||
end
|
||||
|
||||
@notifier.subscribe(nil, listener.new)
|
||||
ActiveSupport::Notifications.instrument("event_name")
|
||||
|
||||
assert_equal "event_name", event_name
|
||||
end
|
||||
end
|
||||
|
||||
class TimedAndMonotonicTimedSubscriberTest < TestCase
|
||||
|
|
Loading…
Reference in New Issue