module EventMachine::Ssh::Callbacks

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

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|

Public Instance Methods

callbacks() click to toggle source

@return [Hash] The registered callbacks

# File lib/em-ssh/callbacks.rb, line 24
def callbacks
  @clbks ||= {}
end
callbacks=(clbks) click to toggle source
# File lib/em-ssh/callbacks.rb, line 28
def callbacks=(clbks)
  @clbks = clbks
end
fire(event, *args) click to toggle source

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. @param [Symbol] event @param [Objects] arguments to pass to all callbacks registered for the given event @param [Array] the results of each callback that was executed

# 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) click to toggle source

Register a callback to be fired when a matching event occurs. The callback will be fired when the event occurs until it returns true. @param [Symbol] event

# 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) click to toggle source

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

# 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