Class: Focus::Host
- Inherits:
-
Object
- Object
- Focus::Host
- Defined in:
- lib/focus/host.rb
Instance Method Summary collapse
- #block!(config) ⇒ Object
- #get_index ⇒ Object
-
#initialize(file = "/etc/hosts") ⇒ Host
constructor
A new instance of Host.
- #overwrite! ⇒ Object
- #read! ⇒ Object
- #restore!(config) ⇒ Object
Constructor Details
#initialize(file = "/etc/hosts") ⇒ Host
Returns a new instance of Host.
3 4 5 6 |
# File 'lib/focus/host.rb', line 3 def initialize(file = "/etc/hosts") @file = file read! end |
Instance Method Details
#block!(config) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/focus/host.rb', line 45 def block!(config) puts "Blocking the hosts".green read! config.block_hosts.each do |block_host| puts block_host.red @data << { host: block_host, ip: "127.0.0.1" } @data << { host: "www.#{block_host}", ip: "127.0.0.1" } end @data.uniq! overwrite! puts "Done!".green end |
#get_index ⇒ Object
8 9 10 11 12 |
# File 'lib/focus/host.rb', line 8 def get_index start_index = @all_lines.find_index { |line| /### FOCUS:start \(automaticaly generated\) ###/i === line } stop_index = @all_lines.find_index { |line| /### FOCUS:stop \(automaticaly generated\) ###/i === line } { start: start_index + 1, stop: stop_index - 1 } if start_index && stop_index end |
#overwrite! ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/focus/host.rb', line 24 def overwrite! index = get_index if index count = index[:stop] - index[:start] @all_lines << "" if @all_lines[index[:start] - 2] != "" @all_lines.slice!(index[:start] - 1, count + 3) else @all_lines << "" if @all_lines.last != "" end @all_lines << "### FOCUS:start (automaticaly generated) ###" @data.each do |managed| @all_lines << "#{managed[:ip]} #{managed[:host]}" end @all_lines << "### FOCUS:stop (automaticaly generated) ###" @all_lines << "" command = "sudo su -c 'echo \"#{@all_lines.join("\n")}\" > #{@file}'" `#{command}` end |
#read! ⇒ Object
14 15 16 17 18 19 20 21 22 |
# File 'lib/focus/host.rb', line 14 def read! @all_lines = File.read(@file).split("\n") index = get_index @data = [] if index selected_lines = @all_lines[index[:start]..index[:stop]] @data = selected_lines.map { |line| line.split(/\s+/) }.map { |ip, host| { ip: ip, host: host } } end end |
#restore!(config) ⇒ Object
58 59 60 61 62 63 |
# File 'lib/focus/host.rb', line 58 def restore!(config) puts "Restoring blocked hosts".green @data = [] overwrite! puts "Done!".green end |