class Madness::Browser
Handles browser launching
Attributes
host[R]
port[R]
Public Class Methods
new(host, port)
click to toggle source
# File lib/madness/browser.rb, line 9 def initialize(host, port) @host, @port = host, port end
Public Instance Methods
open() { |success ? nil : "Failed opening browser (#{join ' '})"| ... }
click to toggle source
Open a web browser if the server is running. This is done in a non-blocking manner, so it can be executed before starting the server. It will yield an error message if it fails, or nil on success.
# File lib/madness/browser.rb, line 42 def open fork do if server_running? success = open! yield success ? nil : "Failed opening browser (#{open_command.join ' '})" else yield "Failed connecting to #{server_url}. Is the server running?" end end end
open!()
click to toggle source
Runs the appropriate command (based on OS) to open a browser.
# File lib/madness/browser.rb, line 54 def open! system *open_command, err: File::NULL, in: File::NULL, out: File::NULL end
open_command()
click to toggle source
Returns the appropriate command (based on OS) to open a browser.
# File lib/madness/browser.rb, line 59 def open_command @open_command ||= [OS.open_file_command, server_url] end
server_running?(retries: 5, delay: 1)
click to toggle source
Returns true if the server is running. Will attempt to connect multiple times. This is designed to assist in running some code after the server has launched.
# File lib/madness/browser.rb, line 23 def server_running?(retries: 5, delay: 1) connected = false attempts = 0 begin connected = Socket.tcp(host, port) rescue sleep delay retry if (attempts += 1) < retries ensure connected.close if connected end !!connected end
server_url()
click to toggle source
Returns a URL based on host, port and MADNESS_FORCE_SSL.
# File lib/madness/browser.rb, line 14 def server_url scheme = ENV['MADNESS_FORCE_SSL'] ? 'https' : 'http' url_host = ['0.0.0.0', '127.0.0.1'].include?(host) ? 'localhost' : host "#{scheme}://#{url_host}:#{port}" end