Last active
December 29, 2020 04:54
-
-
Save bnadlerjr/3269337 to your computer and use it in GitHub Desktop.
Multiple callbacks as blocks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class CallbackList | |
| NOOP_BLOCK = ->(*) { :ok } | |
| def self.[](block) | |
| block ||= NOOP_BLOCK | |
| new.tap { |proxy| block.call(proxy) } | |
| end | |
| def respond_with(callback, *args) | |
| callbacks.fetch(callback, NOOP_BLOCK).call(*args) | |
| end | |
| def method_missing(method, *args, &block) | |
| block ? register_callback(method, block) : super | |
| self | |
| end | |
| private | |
| def callbacks | |
| @callbacks ||= {} | |
| end | |
| def register_callback(method, block) | |
| callbacks[method] = block | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment