Class: On
- Inherits:
-
Object
- Object
- On
- Defined in:
- lib/on.rb,
lib/on/version.rb,
lib/on/test_helper.rb
Overview
Dynamic callbacks for Ruby blocks.
Example
require 'on'
def tweet(, &block)
callback = On.new(:success, :failure, &block)
callback.call :success
rescue => e
callback.call :failure, e.
end
tweet "hello world" do |callback|
callback.on :success do
# handle success
end
callback.on :failure do ||
# handle error message
end
end
Defined Under Namespace
Modules: TestHelper Classes: Callback, InvalidCallback
Constant Summary collapse
- VERSION =
"0.3.2"
Instance Attribute Summary collapse
-
#callback ⇒ Object
readonly
Returns the Callback called or
nil
if none called.
Instance Method Summary collapse
-
#call(name, *args) ⇒ Object
Dispatch callback.
-
#callbacks ⇒ Object
Returns a list of supported callback names provided in the initializer.
-
#initialize(*callbacks, &block) ⇒ On
constructor
A new instance of On.
-
#on(name, &block) ⇒ Object
Handle a callback.
Constructor Details
#initialize(*callbacks, &block) ⇒ On
Returns a new instance of On.
29 30 31 32 33 34 35 |
# File 'lib/on.rb', line 29 def initialize(*callbacks, &block) raise ArgumentError, "please provide at least one callback" if callbacks.empty? raise ArgumentError, "please provide a block" unless block @callbacks = Set.new(callbacks) @callback = nil @block = block end |
Instance Attribute Details
#callback ⇒ Object (readonly)
Returns the Callback called or nil
if none called.
27 28 29 |
# File 'lib/on.rb', line 27 def callback @callback end |
Instance Method Details
#call(name, *args) ⇒ Object
Dispatch callback.
38 39 40 41 42 |
# File 'lib/on.rb', line 38 def call(name, *args) validate_callback!(name) @callback = Callback.new(name, args) @block.call(self) end |
#callbacks ⇒ Object
Returns a list of supported callback names provided in the initializer.
53 54 55 |
# File 'lib/on.rb', line 53 def callbacks @callbacks.to_a end |
#on(name, &block) ⇒ Object
Handle a callback.
45 46 47 48 49 50 |
# File 'lib/on.rb', line 45 def on(name, &block) validate_callback!(name) if @callback && @callback.name == name block.call(*callback.args) end end |