Class: LinuxAdmin::Hosts

Inherits:
Object
  • Object
show all
Includes:
Common
Defined in:
lib/linux_admin/hosts.rb

Constant Summary

Constants included from Common

Common::BIN_DIRS

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Common

#cmd, #cmd?, #run, #run!

Constructor Details

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

Returns a new instance of Hosts.



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

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

Instance Attribute Details

#filenameObject

Returns the value of attribute filename.



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

def filename
  @filename
end

#parsed_fileObject

Returns the value of attribute parsed_file.



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

def parsed_file
  @parsed_file
end

#raw_linesObject

Returns the value of attribute raw_lines.



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

def raw_lines
  @raw_lines
end

Instance Method Details

#hostnameObject



50
51
52
53
# File 'lib/linux_admin/hosts.rb', line 50

def hostname
  result = run(cmd("hostname"))
  result.success? ? result.output.strip : nil
end

#hostname=(name) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/linux_admin/hosts.rb', line 41

def hostname=(name)
  if cmd?("hostnamectl")
    run!(cmd('hostnamectl'), :params => ['set-hostname', name])
  else
    File.write("/etc/hostname", name)
    run!(cmd('hostname'), :params => {:file => "/etc/hostname"})
  end
end

#reloadObject



14
15
16
17
# File 'lib/linux_admin/hosts.rb', line 14

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

#saveObject



19
20
21
22
23
# File 'lib/linux_admin/hosts.rb', line 19

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

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



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

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