Class: Sarb::Application

Inherits:
Object
  • Object
show all
Defined in:
lib/sarb/application.rb

Constant Summary collapse

DEFAULTS =
{
  :host => "127.0.0.1",
  :port => 8080
}

Instance Method Summary collapse

Constructor Details

#initializeApplication

Returns a new instance of Application.



8
9
10
11
12
13
14
15
# File 'lib/sarb/application.rb', line 8

def initialize
  @actions = {}
  @hooks = {
    :connection_open => [method(:connection_open)],
    :connection_close => [method(:connection_close)]
  }
  @connections = Set.new
end

Instance Method Details

#action(name, &block) ⇒ Object



17
18
19
# File 'lib/sarb/application.rb', line 17

def action(name, &block)
  @actions[name.to_sym] = block
end

#connection_close(args) ⇒ Object



34
35
36
# File 'lib/sarb/application.rb', line 34

def connection_close(args)
  @connections.delete(args[:connection])
end

#connection_open(args) ⇒ Object



30
31
32
# File 'lib/sarb/application.rb', line 30

def connection_open(args)
  @connections << args[:connection]
end

#hook(name, &block) ⇒ Object



21
22
23
24
# File 'lib/sarb/application.rb', line 21

def hook(name, &block)
  @hooks[name.to_sym] = [] unless @hooks.has_key?(name.to_sym)
  @hooks[name.to_sym] << block
end

#invoke(connection, message) ⇒ Object



46
47
48
49
# File 'lib/sarb/application.rb', line 46

def invoke(connection, message)
  data = JSON.parse(message)
  @actions[data["action"].to_sym].call(connection, data["args"])
end

#message_all(message, exceptions = Set.new) ⇒ Object



38
39
40
# File 'lib/sarb/application.rb', line 38

def message_all(message, exceptions=Set.new)
  @connections.each { |c| c.message(message) unless exceptions.include?(c) }
end

#new_connection(ws) ⇒ Object



26
27
28
# File 'lib/sarb/application.rb', line 26

def new_connection(ws)
  Connection.setup(self, ws)
end

#run(options = {}) ⇒ Object



42
43
44
# File 'lib/sarb/application.rb', line 42

def run(options = {})
  EventMachine::WebSocket.start(DEFAULTS.merge(options), &method(:new_connection))
end

#trigger(name, args) ⇒ Object



51
52
53
# File 'lib/sarb/application.rb', line 51

def trigger(name, args)
  @hooks[name.to_sym].each { |block| block.call(args) }
end