Class: Epi::Daemon::Sender

Inherits:
Connection
  • Object
show all
Includes:
Exceptions
Defined in:
lib/epi/daemon/sender.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, callback) ⇒ Sender

Returns a new instance of Sender.



34
35
36
37
# File 'lib/epi/daemon/sender.rb', line 34

def initialize(data, callback)
  @callback = callback
  send_object data
end

Class Method Details

.send(what, &callback) ⇒ Object

Send a message to the Epi server

Examples:

Get Epi’s status

Sender.send :status

Add a config file

Sender.send config: {add_paths: ['config.epi']}

Parameters:

  • what (Hash|Symbol)

    Either a symbol being the message type, or a hash with a single key (a symbol) being the message type, and value (a hash) being the message.

Raises:

  • (ArgumentError)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/epi/daemon/sender.rb', line 18

def self.send(what, &callback)

  raise ArgumentError, 'Expected a hash with one key (a symbol) and value (a hash)' unless
      Symbol === what ||
      (Hash === what && what.count == 1 && Symbol === what.keys.first && Hash === what.values.first)

  data = case what
    when Symbol then {type: what}
    when Hash then what.values.first.merge(type: what.keys.first)
    else nil
  end

  EventMachine.connect Daemon.socket_path.to_s, Sender, data, callback

end

Instance Method Details

#receive_object(data) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/epi/daemon/sender.rb', line 39

def receive_object(data)
  if data[:print]
    STDOUT << data[:print]
    return
  end

  if data.key? :result
    result = data[:result]

    if @callback
      @callback.call result
    else
      puts result unless result.nil?
      EM.stop
    end

  elsif data[:error]

    error = data[:error]
    if error[:class] == Fatal.name
      STDERR << error[:message]
      STDERR << "\n"
    else
      STDERR << "#{error[:class]}: #{error[:message]}\n"
      error[:backtrace].each { |x| STDERR << "\t#{x}\n" }
    end

    EM.stop
  end

  close_connection
end