Module: EventMachine::Ssh::Callbacks

Included in:
Connection, EventMachine::Ssh::Connection::Channel::Interactive, 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

#callbacks=(clbks) ⇒ Object

callbacks



28
29
30
# File 'lib/em-ssh/callbacks.rb', line 28

def callbacks=(clbks)
  @clbks = 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



38
39
40
41
42
# File 'lib/em-ssh/callbacks.rb', line 38

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)


47
48
49
50
51
52
53
54
55
56
57
# File 'lib/em-ssh/callbacks.rb', line 47

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.



60
61
62
63
64
65
# File 'lib/em-ssh/callbacks.rb', line 60

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