HostsParser.new(os: :mac).parseResult:
{"127.0.0.1"=>
["localhost",
"kubernetes.docker.internal"],
"255.255.255.255"=>["broadcasthost"],
"::1"=>["localhost"]}
| class UnknowOSError < StandardError | |
| def initialize msg | |
| super(msg) | |
| end | |
| end | |
| class HostsParser | |
| OPERATING_SYSTEMS = %i(mac linux win) | |
| def initialize os:, keep_comment: false | |
| @os = os.downcase.to_sym | |
| raise ::UnknowOSError.new "Unknow OS #{@os}. OS list are: #{OPERATING_SYSTEMS}" unless | |
| OPERATING_SYSTEMS.include?(@os) | |
| @keep_comment = keep_comment | |
| end | |
| def parse | |
| hosts_content_by_os | |
| end | |
| private | |
| attr_reader :os, :keep_comment | |
| def hosts_content_by_os raw_content: false | |
| hosts_file_path = case os | |
| when :mac, :linux | |
| "/etc/hosts" | |
| when :win | |
| "C:\\Windows\\System32\\etc\\drivers\\hosts" | |
| end | |
| hosts_content = ::File.read(hosts_file_path) | |
| return hosts_content if raw_content | |
| hosts_content.split("\n").each_with_object({}) do |line, obj| | |
| line = line.strip | |
| if (line.present? && line !~ /^\#/ && line != "\n") | |
| line = line.split(/\s+/) | |
| hosts_ip = line.shift | |
| (obj[hosts_ip] ||= []).concat(line) | |
| end | |
| end | |
| end | |
| end |