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
)

Parameters:

  • events (Hash)

    event keys



16
17
18
19
# File 'lib/diaspora_federation/callbacks.rb', line 16

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

Instance Method Details

#definition_complete?Boolean

Checks if all callbacks are defined

Returns:

  • (Boolean)


54
55
56
# File 'lib/diaspora_federation/callbacks.rb', line 54

def definition_complete?
  missing_handlers.empty?
end

#missing_handlersHash

Returns all undefined callbacks

Returns:

  • (Hash)

    callback keys



60
61
62
# File 'lib/diaspora_federation/callbacks.rb', line 60

def missing_handlers
  @events - @handlers.keys
end

#on(event, &callback) ⇒ Object

Defines a callback

Examples:

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

Parameters:

  • event (Symbol)

    the event key

  • callback (Proc)

    the callback block

Raises:

  • (ArgumentError)

    if the event key is undefined or has already a handler



31
32
33
34
35
36
# File 'lib/diaspora_federation/callbacks.rb', line 31

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"

Parameters:

  • event (Symbol)

    the event key

Returns:

  • (Object)

    the return-value of the callback

Raises:

  • (ArgumentError)

    if the event key is undefined



46
47
48
49
50
# File 'lib/diaspora_federation/callbacks.rb', line 46

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

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