Module: EventMachine::Ssh::Callbacks

Included in:
Connection, Shell
Defined in:
lib/em-ssh/callbacks.rb

Overview

A simple mixin enabling your objects to allow other objects to register callbacks and fire events.

Examples:

class Connection
  include Callbacks
  # ...
end

connection = Connection.new(...)
cb = connection.on(:data) do |data|
  @version << data
  if @version[-1] == "\n"
    @version.chomp!
    raise SshError.new("incompatible SSH version `#{@version}'") unless @version.match(/^SSH-(1\.99|2\.0)-/)
    connection.send_data("#{PROTO_VERSION}\r\n")
    cb.cancel
    connection.fire(:version_negotiated)
  end # @header[-1] == "\n"
end #  |data|

Defined Under Namespace

Classes: Callback

Instance Method Summary collapse

Instance Method Details

#callbacksHash

Returns The registered callbacks.

Returns:

  • (Hash)

    The registered callbacks



24
25
26
# File 'lib/em-ssh/callbacks.rb', line 24

def callbacks
  @clbks ||= {}
end

#fire(event, *args) ⇒ Object

Signal that an event has occured. Each callback will receive whatever args are passed to fire, or the object that the event was fired upon.

Parameters:

  • event (Symbol)
  • arguments (Objects)

    to pass to all callbacks registered for the given event

  • the (Array)

    results of each callback that was executed



34
35
36
37
38
# File 'lib/em-ssh/callbacks.rb', line 34

def fire(event, *args)
  #log.debug("#{self}.fire(#{event.inspect}, #{args})")
  args = self if args.empty?
  (callbacks[event] ||= []).clone.map { |cb| cb.call(*args) }
end

#on(event, &blk) ⇒ Object

Register a callback to be fired when a matching event occurs. The callback will be fired when the event occurs until it returns true.

Parameters:

  • event (Symbol)


43
44
45
46
47
48
49
50
51
52
53
# File 'lib/em-ssh/callbacks.rb', line 43

def on(event, &blk)
  #log.debug("#{self}.on(#{event.inspect}, #{blk})")
  if block_given?
    raise "event (#{event.inspect}) must be a symbol when a block is given" unless event.is_a?(Symbol)
    return Callback.new(self, event, &blk).tap{|cb| (callbacks[event] ||= []).push(cb) }
  end # block_given?

  raise "event (#{event.inspect}) must be a Callback when a block is not given" unless event.is_a?(Callback)
  (callbacks[event] ||= []).push(event)
  return event
end

#on_next(event, &blk) ⇒ Object

Registers a callback that will be canceled after the first time it is called.



56
57
58
59
60
61
# File 'lib/em-ssh/callbacks.rb', line 56

def on_next(event, &blk)
  cb = on(event) do |*args|
    cb.cancel
    blk.call(*args)
  end # |*args|
end