Class: RandomPort::Pool

Inherits:
Object
  • Object
show all
Defined in:
lib/random-port/pool.rb

Overview

Pool of TPC ports.

The class is NOT thread-safe!

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2018 Yegor Bugayenko

License

MIT

Constant Summary collapse

SINGLETON =

Application wide pool of ports

Pool.new

Instance Method Summary collapse

Constructor Details

#initializePool

Returns a new instance of Pool.


36
37
38
# File 'lib/random-port/pool.rb', line 36

def initialize
  @ports = []
end

Instance Method Details

#acquireObject


43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/random-port/pool.rb', line 43

def acquire
  loop do
    server = TCPServer.new('127.0.0.1', 0)
    port = server.addr[1]
    server.close
    next if @ports.include?(port)
    @ports << port
    return port unless block_given?
    yield port
    @ports.delete(port)
    break
  end
end

#release(port) ⇒ Object


57
58
59
# File 'lib/random-port/pool.rb', line 57

def release(port)
  @ports.delete(port)
end