Skip to content

Instantly share code, notes, and snippets.

@joshnesbitt
Created May 14, 2012 11:30
Show Gist options
  • Select an option

  • Save joshnesbitt/2693475 to your computer and use it in GitHub Desktop.

Select an option

Save joshnesbitt/2693475 to your computer and use it in GitHub Desktop.
#! /usr/bin/ruby
class HostsFile
attr_accessor :lines
def initialize(path = '/etc/hosts')
@file = File.open(path, 'r')
@entries = []
parse
end
def parse
@file.each_line do |line|
unless invalid_line?(line)
@entries << parse_line(line)
end
end
end
def includes?(name)
if (entries = fuzzy_entry_match(name)).empty?
puts "No entries found under the name '#{name}'"
else
puts "#{entries.size} entries found:", ''
entries.each { |e| puts "* #{e}" }
end
end
private
def parse_line(line)
parts = line.strip!.split(' ')
HostsEntry.new(parts[0], parts[1])
end
def invalid_line?(line)
line.strip.empty? || line.include?('#')
end
def fuzzy_entry_match(name)
@entries.reject { |l| !l.name.include?(name) }.sort
end
end
class HostsEntry < Struct.new(:address, :name)
def to_s
[ self.address, self.name ].join(' ')
end
def <=>(other)
self.address <=> other.address
end
end
hosts = HostsFile.new
hosts.includes?(ARGV[0] || '')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment