Class: On

Inherits:
Object
  • Object
show all
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(message, &block)
  callback = On.new(:success, :failure, &block)
  callback.call :success
rescue => e
  callback.call :failure, e.message
end

tweet "hello world" do |callback|
  callback.on :success do
    # handle success
  end
  callback.on :failure do |error_message|
    # handle error message
  end
end

Defined Under Namespace

Modules: TestHelper Classes: Callback, InvalidCallback

Constant Summary collapse

VERSION =
"1.0.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*callbacks, &block) ⇒ On

Returns a new instance of On

Raises:

  • (ArgumentError)

28
29
30
31
32
33
34
# File 'lib/on.rb', line 28

def initialize(*callbacks, &block)
  raise ArgumentError, "please provide at least one callback" if callbacks.empty?
  raise ArgumentError, "please provide a block" unless block
  @callbacks  = callbacks
  @callback   = nil
  @block      = block
end

Instance Attribute Details

#callbackObject (readonly)

Returns the Callback called or nil if none called.


26
27
28
# File 'lib/on.rb', line 26

def callback
  @callback
end

Instance Method Details

#call(name, *args) ⇒ Object

Dispatch callback.


37
38
39
40
41
# File 'lib/on.rb', line 37

def call(name, *args)
  validate_callback!(name)
  @callback = Callback.new(name, args)
  @block.call(self)
end

#callbacksObject

Returns a list of supported callback names provided in the initializer.


52
53
54
# File 'lib/on.rb', line 52

def callbacks
  @callbacks.to_a
end

#on(name, &block) ⇒ Object

Handle a callback.


44
45
46
47
48
49
# File 'lib/on.rb', line 44

def on(name, &block)
  validate_callback!(name)
  if @callback && @callback.name == name
    block.call(*callback.args)
  end
end