Class: Mimic::Server

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/mimic/server.rb

Instance Method Summary collapse

Instance Method Details

#listening?(host, port) ⇒ Boolean

courtesy of is.gd/eoYho

Returns:

  • (Boolean)


39
40
41
42
43
44
45
46
47
48
49
# File 'lib/mimic/server.rb', line 39

def listening?(host, port)
  begin
    socket = TCPSocket.new(host, port)
    socket.close unless socket.nil?
    true
  rescue Errno::ECONNREFUSED, SocketError,
    Errno::EBADF,           # Windows
    Errno::EADDRNOTAVAIL    # Windows
    false
  end
end

#loggerObject



7
8
9
# File 'lib/mimic/server.rb', line 7

def logger
  @logger ||= Logger.new(StringIO.new)
end

#serve(app, options) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/mimic/server.rb', line 11

def serve(app, options)
  if options[:fork]
    @thread = Thread.fork do
      start_service(app, options)
    end

    wait_for_service(app.hostname, options[:port])

  else
    start_service(app, options)
  end
end

#shutdownObject



33
34
35
# File 'lib/mimic/server.rb', line 33

def shutdown
  Thread.kill(@thread) if @thread
end

#start_service(app, options) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/mimic/server.rb', line 24

def start_service(app, options)
  Rack::Handler::Thin.run(app.url_map, {
    :Host       => options[:Host] || 'localhost',
    :Port       => options[:port],
    :Logger     => logger,
    :AccessLog  => logger
  })
end

#wait_for_service(host, port, timeout = 5) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/mimic/server.rb', line 51

def wait_for_service(host, port, timeout = 5)
  start_time = Time.now

  until listening?(host, port)
    if timeout && (Time.now > (start_time + timeout))
      raise SocketError.new("Socket did not open within #{timeout} seconds")
    end
  end
end