Class: Hosts

Inherits:
Object
  • Object
show all
Defined in:
lib/hoster/hosts.rb

Constant Summary collapse

@@default_hosts_path =
'/etc/hosts'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hosts_path = @@default_hosts_path) ⇒ Hosts

Returns a new instance of Hosts.



12
13
14
15
# File 'lib/hoster/hosts.rb', line 12

def initialize(hosts_path = @@default_hosts_path)
  @hosts_path = hosts_path
  @entries    = extract_entries
end

Instance Attribute Details

#entriesObject (readonly)

Returns the value of attribute entries.



10
11
12
# File 'lib/hoster/hosts.rb', line 10

def entries
  @entries
end

Instance Method Details

#add(host, ip_address = "127.0.0.1") ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/hoster/hosts.rb', line 21

def add(host, ip_address = "127.0.0.1")
  if @entries.has_key?(ip_address)
    @entries[ip_address] << host
  else
    @entries[ip_address] = [host]
  end
  write_changes!
end

#display(ip_address = "127.0.0.1") ⇒ Object



46
47
48
# File 'lib/hoster/hosts.rb', line 46

def display(ip_address="127.0.0.1")
  puts "  #{ip_address} = #{@entries.values_at(ip_address).join(' ')}\n"
end

#dumpObject



17
18
19
# File 'lib/hoster/hosts.rb', line 17

def dump
  File.open(@hosts_path,"r") { |f| f.read }
end

#modify(host, ip_address) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/hoster/hosts.rb', line 35

def modify(host, ip_address)
  host_exists = false
  @entries.each_value { |v| host_exists = true if v.include?(host) }
  if host_exists
    remove(host)
    add(host,ip_address)
  else
    raise "#{host} does not exist. Please use 'add' command instead."
  end
end

#remove(host) ⇒ Object



30
31
32
33
# File 'lib/hoster/hosts.rb', line 30

def remove(host)
  @entries.each_pair { |key,value| value.delete_if { |v| v == host } }
  write_changes!
end