Sha256: 936299409706bb1b5b050afbbe984caaf88297ff8770b07f4e4bdcf273ffbf68

Contents?: true

Size: 1.08 KB

Versions: 4

Compression:

Stored size: 1.08 KB

Contents

# Class for parsing and writing /etc/hosts file

class Hosts
  def initialize
    @preamble = ""
    @postamble = ""
    @config = {}

    parse
  end

  attr_reader :config

  def save
    File.open('.tmp.hosts','w') do |f|
      f.write @preamble
      f.puts BEGIN_LINE

      @config.each do |ip, host|
        f.puts "#{ip}\t#{host}"
      end

      f.puts END_LINE
      f.write @postamble
    end
    system "sudo mv .tmp.hosts /etc/hosts"
  end

  private

  BEGIN_LINE = "#### BEGIN BUM ####"
  END_LINE = "#### END BUM ####"

  def parse
    state = :preamble

    File.open('/etc/hosts').each_line do |line|
      case state
      when :preamble
        if line.include? BEGIN_LINE
          state = :bum
        else
          @preamble << line
        end
      when :bum
        if line.include? END_LINE
          state = :postamble
        else
          if line.strip =~ /^#/
            # skip
          else
            ip, host = line.split(/\s+/)
            @config[ip] = host
          end
        end
      when :postamble
        @postamble << line
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
bum-0.0.4 lib/hosts.rb
bum-0.0.3 lib/hosts.rb
bum-0.0.2 lib/hosts.rb
bum-0.0.1 lib/hosts.rb