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 =
"0.3.2"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*callbacks, &block) ⇒ On

Returns a new instance of On.

Raises:

  • (ArgumentError)


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

#callbackObject (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

#callbacksObject

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