Class: Madness::Browser

Inherits:
Object
  • Object
show all
Defined in:
lib/madness/browser.rb

Overview

Handles browser launching

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port) ⇒ Browser

Returns a new instance of Browser.



9
10
11
12
# File 'lib/madness/browser.rb', line 9

def initialize(host, port)
  @host = host
  @port = port
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



7
8
9
# File 'lib/madness/browser.rb', line 7

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



7
8
9
# File 'lib/madness/browser.rb', line 7

def port
  @port
end

Instance Method Details

#openObject

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.



42
43
44
45
46
47
48
49
50
51
# 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!Object

Runs the appropriate command (based on OS) to open a browser.



54
55
56
# File 'lib/madness/browser.rb', line 54

def open!
  system(*open_command, err: File::NULL, in: File::NULL, out: File::NULL)
end

#open_commandObject

Returns the appropriate command (based on OS) to open a browser.



59
60
61
# 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) ⇒ Boolean

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.

Returns:

  • (Boolean)


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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_urlObject

Returns a URL based on host, port and MADNESS_FORCE_SSL.



15
16
17
18
# File 'lib/madness/browser.rb', line 15

def server_url
  url_host = ['0.0.0.0', '127.0.0.1'].include?(host) ? 'localhost' : host
  "http://#{url_host}:#{port}"
end