noprocrast/lib/noprocast.rb

68 lines
1.6 KiB
Ruby
Raw Permalink Normal View History

2010-11-10 15:08:57 +00:00
require 'fileutils'
class Noprocast
class << self
def default_hosts
['news.ycombinator.com', 'twitter.com', 'facebook.com', 'reddit.com']
end
def deny_file_path
File.expand_path("~/.noprocast")
end
def current_hosts
setup_deny_file_if_required!
File.read(deny_file_path).split(/\n/).select { |line| line.match(/[a-zA-Z0-9]/) }.map(&:strip)
2010-11-10 15:08:57 +00:00
end
def hosts_file_content
File.read("/etc/hosts")
end
def activate!
backup_hosts_file_if_required!
deactivate! # ensure that /etc/hosts is clean
File.open("/etc/hosts", 'a') do |file|
file << "\n\n# noprocast start\n#{current_hosts.map { |host| "127.0.0.1 #{host}" }.join("\n")}\n# noprocast end"
end
2010-11-11 08:30:18 +00:00
system "dscacheutil -flushcache" # only for OSX >= 10.5: flush the DNS cache
2010-11-10 15:08:57 +00:00
end
def deactivate!
clean_hosts = hosts_file_content.gsub(/(\n\n)?\# noprocast start.*\# noprocast end/m, '')
File.open("/etc/hosts", 'w') do |file|
file << clean_hosts
end
end
def active?
hosts_file_content.match(/\# noprocast start/)
end
def status_message
active? ? "noprocast enabled for #{current_hosts.size} hosts" : "noprocast disabled"
end
def backup_hosts_file_if_required!
unless File.exists?("/etc/.hosts.noprocastbackup")
FileUtils.cp("/etc/hosts", "/etc/.hosts.noprocastbackup")
end
end
def setup_deny_file_if_required!
unless File.exists?(deny_file_path)
File.open(deny_file_path, 'w') do |file|
file << default_hosts.join("\n")
end
end
end
def edit!
2010-11-11 08:30:18 +00:00
setup_deny_file_if_required!
2010-11-10 15:08:57 +00:00
editor = ENV['EDITOR'] || 'vi'
system "#{editor} #{deny_file_path}"
end
end
end