class RubyYacht::Runner::UpdateHosts

This class provides a command for updating the hosts file.

Public Class Methods

command() click to toggle source

The name of the command.

# File lib/ruby_yacht/runner/update_hosts.rb, line 5
def self.command; 'update_hosts'; end
description() click to toggle source

The description of the command.

# File lib/ruby_yacht/runner/update_hosts.rb, line 8
def self.description
  "Add entries for your app domains to your hosts file"
end

Public Instance Methods

current_host_contents() click to toggle source

The current contents of the hosts file.

# File lib/ruby_yacht/runner/update_hosts.rb, line 13
def current_host_contents
  File.read('/etc/hosts')
end
hosts_file_entries(project, ip_address) click to toggle source

This method gets the contents of the hosts file for a project.

### Parameters

  • **project: RubyYacht::Project** The project we are working on.

  • **ip_address: String** The IP address that docker listens

    on.

### Returns An Array with the new lines for the hosts file.

# File lib/ruby_yacht/runner/update_hosts.rb, line 60
def hosts_file_entries(project, ip_address)
  system_prefix = project.system_prefix
  header = "# #{system_prefix} docker containers"
  new_hosts = ["", header]
  
  project.web_servers.each do |web_server|
    main_domain = web_server.domain
  
    domains = [main_domain]
    apps = project.apps.select { |app| app.name != system_prefix }
    domains += apps.map { |app| "#{app.name}.#{main_domain}" }
  
    new_hosts += domains.map { |domain| "#{ip_address}    #{domain}" }
  end
  new_hosts
end
run() click to toggle source

This method runs the logic of the command.

# File lib/ruby_yacht/runner/update_hosts.rb, line 18
def run
  ip_address = get_machine_info('.Driver.IPAddress')
  if ip_address == ""
    ip_address = "127.0.0.1"
  end
  
  current_hosts = current_host_contents.split("\n")
  new_hosts = current_hosts.select do |entry|
    projects.none? do |project|
      project.web_servers.any? do |server|
        entry.include?(server.domain) || entry.include?("#{project.system_prefix} docker containers")
      end
    end
  end
  
  new_hosts.pop while new_hosts.any? && new_hosts.last.length == 0
  
  new_hosts += projects.map { |p| self.hosts_file_entries(p, ip_address) }.flatten
  
  FileUtils.mkdir_p('tmp')
  File.open(File.join('tmp', 'hosts'), 'w') do |file|
    file.write(new_hosts.join("\n"))
  end
  
  timestamp = Time.now.utc.strftime('%Y%m%d%H%M%S')
  log "Please enter your password so that we can update the hosts file"
  sudo_command = backtick('which sudo').strip
  system "#{sudo_command} cp /etc/hosts /etc/hosts.#{timestamp}.backup"
  system "#{sudo_command} cat tmp/hosts > /etc/hosts"
  true
end