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
- .build_block(hostnames) ⇒ Object
- .clean ⇒ Object
- .file ⇒ Object
- .read ⇒ Object
- .strip_block(text) ⇒ Object
-
.sync(hostnames) ⇒ Object
Replace the managed block with one 127.0.0.1 line per hostname.
- .write(content) ⇒ Object
Class Method Details
.build_block(hostnames) ⇒ Object
27 28 29 30 31 |
# File 'lib/portless/hosts.rb', line 27 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 |
.clean ⇒ Object
23 24 25 |
# File 'lib/portless/hosts.rb', line 23 def clean write(strip_block(read)) end |
.file ⇒ Object
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 |
.read ⇒ Object
37 38 39 |
# File 'lib/portless/hosts.rb', line 37 def read File.exist?(file) ? File.read(file) : "" end |
.strip_block(text) ⇒ Object
33 34 35 |
# File 'lib/portless/hosts.rb', line 33 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
41 42 43 44 45 |
# File 'lib/portless/hosts.rb', line 41 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 |