Module: Portless::Hosts

Defined in:
lib/portless/hosts.rb

Overview

/etc/hosts management for resolvers that don't special-case .localhost (Safari, custom TLDs). Chrome/Firefox/Edge auto-resolve *.localhost, so this is a fallback. Entries live in a fenced, idempotent block. Mirrors portless's hosts.ts.

Class Method Summary collapse

Class Method Details

.build_block(hostnames) ⇒ Object



32
33
34
35
36
# File 'lib/portless/hosts.rb', line 32

def build_block(hostnames)
  return "" if hostnames.empty?
  lines = hostnames.uniq.map { |h| "127.0.0.1\t#{h}" }
  [ Constants::HOSTS_BEGIN, *lines, Constants::HOSTS_END ].join("\n")
end

.cleanObject



23
24
25
# File 'lib/portless/hosts.rb', line 23

def clean
  write(strip_block(read))
end

.fileObject



13
14
15
# File 'lib/portless/hosts.rb', line 13

def file
  Constants::WINDOWS ? File.join(ENV.fetch("SystemRoot", "C:/Windows"), "System32/drivers/etc/hosts") : "/etc/hosts"
end

.managed_hostnamesObject



27
28
29
30
# File 'lib/portless/hosts.rb', line 27

def managed_hostnames
  read[/#{Regexp.escape(Constants::HOSTS_BEGIN)}\n(.*?)#{Regexp.escape(Constants::HOSTS_END)}/m, 1]
    .to_s.scan(/^\s*127\.0\.0\.1\s+(\S+)/).flatten
end

.readObject



42
43
44
# File 'lib/portless/hosts.rb', line 42

def read
  File.exist?(file) ? File.read(file) : ""
end

.strip_block(text) ⇒ Object



38
39
40
# File 'lib/portless/hosts.rb', line 38

def strip_block(text)
  text.gsub(/\n*#{Regexp.escape(Constants::HOSTS_BEGIN)}.*?#{Regexp.escape(Constants::HOSTS_END)}\n*/m, "\n")
end

.sync(hostnames) ⇒ Object

Replace the managed block with one 127.0.0.1 line per hostname.



18
19
20
21
# File 'lib/portless/hosts.rb', line 18

def sync(hostnames)
  block = build_block(hostnames)
  write(strip_block(read) + (block.empty? ? "" : "\n#{block}\n"))
end

.write(content) ⇒ Object



46
47
48
49
50
# File 'lib/portless/hosts.rb', line 46

def write(content)
  File.write(file, content.gsub(/\n{3,}/, "\n\n"))
rescue Errno::EACCES
  raise Error, "writing #{file} needs root — re-run via sudo (rb-portless hosts sync)"
end