Class: Simultaneous::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/simultaneous/connection.rb

Constant Summary collapse

TCP_CONNECTION_MATCH =
%r{^([^/]+):(\d+)}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection_string, options = {}) ⇒ Connection

Returns a new instance of Connection.



13
14
15
16
17
18
19
20
21
22
# File 'lib/simultaneous/connection.rb', line 13

def initialize(connection_string, options = {})
  @options = options
  @tcp = false
  if connection_string =~ TCP_CONNECTION_MATCH
    @tcp = true
    @host, @port = $1, $2.to_i
  else
    @socket = connection_string
  end
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



11
12
13
# File 'lib/simultaneous/connection.rb', line 11

def options
  @options
end

Class Method Details

.tcp(host, port) ⇒ Object



7
8
9
# File 'lib/simultaneous/connection.rb', line 7

def self.tcp(host, port)
  "#{host}:#{port}"
end

Instance Method Details

#async_socket(handler, &block) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/simultaneous/connection.rb', line 44

def async_socket(handler, &block)
  if tcp?
    EventMachine.connect(@host, @port, handler, &block)
  else
    EventMachine.connect(@socket, handler, &block)
  end
end

#open_sync_socketObject



66
67
68
69
70
71
72
# File 'lib/simultaneous/connection.rb', line 66

def open_sync_socket
  if tcp?
    TCPSocket.new(@host, @port)
  else
    UNIXSocket.new(@socket)
  end
end

#set_socket_permissions(socket) ⇒ Object



74
75
76
77
78
79
# File 'lib/simultaneous/connection.rb', line 74

def set_socket_permissions(socket)
  if File.exist?(socket)
    File.chmod(00777, socket)
    File.chown(nil, options[:gid], socket) if options[:gid]
  end
end

#start_server(handler, &block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/simultaneous/connection.rb', line 32

def start_server(handler, &block)
  if tcp?
    EventMachine::start_server(@host, @port, handler, &block)
  else
    EventMachine::start_server(@socket, handler, &block)
    set_socket_permissions(@socket)
    EM.add_shutdown_hook {
      FileUtils.rm(@socket) if @socket and File.exist?(@socket)
    }
  end
end

#sync_socketObject



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/simultaneous/connection.rb', line 52

def sync_socket
  socket = open_sync_socket
  if block_given?
    begin
      yield(socket)
      socket.flush
      socket.close_write
    ensure
      socket.close if socket rescue nil
    end
  end
  socket
end

#tcp?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/simultaneous/connection.rb', line 24

def tcp?
  @tcp
end

#unix?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/simultaneous/connection.rb', line 28

def unix?
  !@tcp
end