lib/rack/handler/toycol.rb in toycol-0.1.0 vs lib/rack/handler/toycol.rb in toycol-0.2.0

- old
+ new

@@ -1,25 +1,60 @@ # frozen_string_literal: true +require "rack" require "rack/handler" -require "rack/handler/puma" module Rack module Handler class Toycol - def self.run(app, options = {}) - if (child_pid = fork) - environment = ENV["RACK_ENV"] || "development" - default_host = environment == "development" ? "localhost" : "0.0.0.0" + class << self + attr_writer :preferred_background_server, :host, :port - host = options.delete(:Host) || default_host - port = options.delete(:Port) || "9292" + def run(app, _ = {}) + @app = app + @host ||= ::Toycol::DEFAULT_HOST + @port ||= "9292" - ::Toycol::Proxy.new(host, port).start - Process.waitpid(child_pid) - else - puts "Toycol starts Puma in single mode, listening on unix://#{::Toycol::UNIX_SOCKET_PATH}" - Rack::Handler::Puma.run(app, **{ Host: ::Toycol::UNIX_SOCKET_PATH, Silent: true }) + if (child_pid = fork) + ::Toycol::Proxy.new(@host, @port).start + Process.waitpid(child_pid) + else + run_background_server + end + end + + private + + def select_background_server + case @preferred_background_server + when "puma" + return "puma" if puma_requireable? + + puts "Puma is not installed in your environment." + raise LoadError + when nil + puma_requireable? ? "puma" : "build_in" + else + "build_in" + end + end + + def puma_requireable? + require "rack/handler/puma" + true + rescue LoadError + false + end + + def run_background_server + case select_background_server + when "puma" + puts "Toycol starts Puma in single mode, listening on unix://#{::Toycol::UNIX_SOCKET_PATH}" + Rack::Handler::Puma.run(@app, **{ Host: ::Toycol::UNIX_SOCKET_PATH, Silent: true }) + else + puts "Toycol starts build-in server, listening on unix://#{::Toycol::UNIX_SOCKET_PATH}" + ::Toycol::Server.run(@app, **{ Path: ::Toycol::UNIX_SOCKET_PATH, Port: @port }) + end end end end register :toycol, Toycol