$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) module Hosts def self.search(pattern='') regex = Regexp.new(pattern) results = [] addresses.each do |address, entries| if address =~ regex entries.each do |hostname, editable| results << [address, hostname, editable] end end end hostnames.each do |hostname, entries| if hostname =~ regex entries.each do |address, editable| results << [address, hostname, editable] end end end results.uniq.sort do |a,b| r = 0 r = a[0] <=> b[0] if r == 0 r = a[1] <=> b[1] if r == 0 r end end def self.hostnames @hostnames ||= {} end def self.addresses @addresses ||= {} end def self.hostname(hostname) hostnames[hostname] ||= {} end def self.address(address) addresses[address] ||= {} end def self.editable?(hostname, address) return true if hostname(hostname).nil? or hostname(hostname)[address].nil? return hostname(hostname)[address] end def self.add(hostname, address, editable=true) if editable?(hostname, address) address(address)[hostname] = editable hostname(hostname)[address] = editable end end def self.remove(hostname, address) if editable?(hostname, address) hostname(hostname).delete(address) address(address).delete(hostname) end end def self.lines @lines ||= [] end def self.read editable = false lines.clear File.readlines('/etc/hosts').collect{ |line| line.strip }.each do |line| lines << line unless editable editable = true if line == '### AUTOGENERATED HOST ENTRIES ###' next if line =~ /^\s+|#.*$/ segements = line.split(/\s+/) address = segements.shift segements.each do |segement| add(segement, address, editable) end end lines << '### AUTOGENERATED HOST ENTRIES ###' unless editable end def self.write begin File.open('/etc/hosts', 'w+') do |f| lines.each { |l| f.puts l } addresses.each do |address, hostnames| editable_hostnames = [] hostnames.each do |hostname, editable| editable_hostnames << hostname if editable end f.puts "#{address} #{editable_hostnames.join(' ')}" unless editable_hostnames.empty? end end rescue => e puts e exit(1) end end end