Class: CallbackCollection

Inherits:
Object
  • Object
show all
Defined in:
lib/callback_collection.rb,
lib/callback_collection/version.rb

Overview

Stores named callbacks during initialization, then exposes thread-safe reads.

Examples:

callbacks = CallbackCollection.new do |collection|
  collection.success { |value| "Received #{value}" }
end

callbacks.respond_with(:success, "data")
# => "Received data"

Constant Summary collapse

VERSION =
"0.2.1"

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ CallbackCollection

Returns a new instance of CallbackCollection.

Yields:

  • (_self)

Yield Parameters:



30
31
32
33
34
35
# File 'lib/callback_collection.rb', line 30

def initialize
  callbacks
  yield(self) if block_given?
  callbacks.freeze
  freeze
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/callback_collection.rb', line 51

def method_missing(method_name, *args, &block)
  if block
    store_callback(method_name, block)
  else
    super
  end
end

Instance Method Details

#register(callback, receiver, method_name = callback) ⇒ Object



37
38
39
# File 'lib/callback_collection.rb', line 37

def register(callback, receiver, method_name = callback)
  store_callback(callback, RegisteredCallback.new(receiver, method_name))
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/callback_collection.rb', line 59

def respond_to_missing?(method_name, include_private = false)
  callbacks.key?(method_name) || super
end

#respond_with(callback, *args, **kwargs, &block) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/callback_collection.rb', line 41

def respond_with(callback, *args, **kwargs, &block)
  handler = callbacks.fetch(callback) do
    raise NoMethodError, "No callback '#{callback}' is defined."
  end

  return handler.call(*args, &block) if kwargs.empty?

  handler.call(*args, **kwargs, &block)
end