Class: LinuxAdmin::Hosts

Inherits:
LinuxAdmin show all
Defined in:
lib/linux_admin/hosts.rb

Constant Summary

Constants inherited from LinuxAdmin

VERSION

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Common

#cmd, #run, #run!

Constructor Details

#initialize(filename = "/etc/hosts") ⇒ Hosts

Returns a new instance of Hosts.



7
8
9
10
# File 'lib/linux_admin/hosts.rb', line 7

def initialize(filename = "/etc/hosts")
  @filename = filename
  self.reload
end

Instance Attribute Details

#filenameObject

Returns the value of attribute filename.



3
4
5
# File 'lib/linux_admin/hosts.rb', line 3

def filename
  @filename
end

#parsed_fileObject

Returns the value of attribute parsed_file.



5
6
7
# File 'lib/linux_admin/hosts.rb', line 5

def parsed_file
  @parsed_file
end

#raw_linesObject

Returns the value of attribute raw_lines.



4
5
6
# File 'lib/linux_admin/hosts.rb', line 4

def raw_lines
  @raw_lines
end

Instance Method Details

#reloadObject



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

def reload
  @raw_lines = File.read(@filename).split("\n")
  parse_file
end

#saveObject



17
18
19
20
21
# File 'lib/linux_admin/hosts.rb', line 17

def save
  cleanup_empty
  @raw_lines = assemble_lines
  File.write(@filename, @raw_lines.join("\n"))
end

#update_entry(address, hostname, comment = nil) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/linux_admin/hosts.rb', line 23

def update_entry(address, hostname, comment = nil)
  # Delete entries for this hostname first
  @parsed_file.each {|i| i[:hosts].to_a.delete(hostname)}

  # Add entry
  line_number = @parsed_file.find_path(address).first

  if line_number.blank?
    @parsed_file.push({:address => address, :hosts => [hostname], :comment => comment})
  else
    new_hosts = @parsed_file.fetch_path(line_number, :hosts).to_a.push(hostname)
    @parsed_file.store_path(line_number, :hosts, new_hosts)
    @parsed_file.store_path(line_number, :comment, comment) if comment
  end
end