Class: Mimic::Server

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

Instance Method Summary collapse

Instance Method Details

#listening?(host, port) ⇒ Boolean

courtesy of is.gd/eoYho

Returns:

  • (Boolean)


77
78
79
80
81
82
83
84
85
86
87
# File 'lib/mimic.rb', line 77

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



46
47
48
# File 'lib/mimic.rb', line 46

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

#serve(app, options) ⇒ Object



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

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

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

  else
    start_service(app, options)
  end
end

#shutdownObject



71
72
73
# File 'lib/mimic.rb', line 71

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

#start_service(app, options) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/mimic.rb', line 63

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

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



89
90
91
92
93
94
95
96
97
# File 'lib/mimic.rb', line 89

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