Sha256: bfc5777acd06d4151d3ac7e152c84d0c1aaf51d6f74b12cd44f2bf40c40f693f

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 KB

Contents

module Backport
  # The Backport server controller.
  #
  class Machine
    def initialize
      @stopped = true
    end

    # Run the machine. If a block is provided, it gets executed before the
    # maching starts its main loop. The main loop blocks program execution
    # until the machine is stopped.
    #
    # @return [void]
    def run
      return unless stopped?
      servers.clear
      @stopped = false
      yield if block_given?
      run_server_thread
    end

    # Stop the machine.
    #
    # @return [void]
    def stop
      servers.map(&:stop)
      servers.clear
      @stopped = true
    end

    # True if the machine is stopped.
    #
    def stopped?
      @stopped ||= false
    end

    # Add a server to the machine. The server will be started when the machine
    # starts. If the machine is already running, the server will be started
    # immediately.
    #
    # @param server [Server::Base]
    # @return [void]
    def prepare server
      servers.push server
      server.start unless stopped?
    end

    # @return [Array<Server::Base>]
    def servers
      @servers ||= []
    end

    def tick
      servers.delete_if(&:stopped?)
      stop if servers.empty?
      servers.each(&:tick)
    end

    private

    def run_server_thread
      servers.map(&:start)
      until stopped?
        tick
        sleep 0.001
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
backport-0.3.0 lib/backport/machine.rb