Class: DiasporaFederation::Callbacks

Inherits:
Object
  • Object
show all
Defined in:
lib/diaspora_federation/callbacks.rb

Overview

Callbacks are used to communicate with the application. They are called to fetch data and after data is received.

Instance Method Summary collapse

Constructor Details

#initialize(events) ⇒ Callbacks

Initializes a new Callbacks object with the event-keys that need to be defined

Examples:

Callbacks.new i(
  some_event
  another_event
)

14
15
16
17
# File 'lib/diaspora_federation/callbacks.rb', line 14

def initialize(events)
  @events   = events
  @handlers = {}
end

Instance Method Details

#definition_complete?Boolean

Checks if all callbacks are defined


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

def definition_complete?
  missing_handlers.empty?
end

#missing_handlersHash

Returns all undefined callbacks


58
59
60
# File 'lib/diaspora_federation/callbacks.rb', line 58

def missing_handlers
  @events - @handlers.keys
end

#on(event, &callback) ⇒ Object

Defines a callback

Examples:

callbacks.on :some_event do |arg1|
  # do something
end

Raises:

  • (ArgumentError)

    if the event key is undefined or has already a handler


29
30
31
32
33
34
# File 'lib/diaspora_federation/callbacks.rb', line 29

def on(event, &callback)
  raise ArgumentError, "Undefined event #{event}" unless @events.include? event
  raise ArgumentError, "Already defined event #{event}" if @handlers.has_key? event

  @handlers[event] = callback
end

#trigger(event, *args) ⇒ Object

Triggers a callback

Examples:

callbacks.trigger :some_event, "foo"

Raises:

  • (ArgumentError)

    if the event key is undefined


44
45
46
47
48
# File 'lib/diaspora_federation/callbacks.rb', line 44

def trigger(event, *args)
  raise ArgumentError, "Undefined event #{event}" unless @events.include? event

  @handlers[event].call(*args)
end