Class: LinuxAdmin::Hosts

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

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#add_alias(address, hostname, comment = nil) ⇒ Object Also known as: update_entry



23
24
25
# File 'lib/linux_admin/hosts.rb', line 23

def add_alias(address, hostname, comment = nil)
  add_name(address, hostname, false, comment)
end

#hostnameObject



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

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

#hostname=(name) ⇒ Object



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

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

#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") + "\n")
end

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



33
34
35
# File 'lib/linux_admin/hosts.rb', line 33

def set_canonical_hostname(address, hostname, comment = nil)
  add_name(address, hostname, true, comment)
end

#set_loopback_hostname(hostname, comment = nil) ⇒ Object



29
30
31
# File 'lib/linux_admin/hosts.rb', line 29

def set_loopback_hostname(hostname, comment = nil)
  ["::1", "127.0.0.1"].each { |address| add_name(address, hostname, true, comment, false) }
end