2010-11-10 15:08:57 +00:00
|
|
|
require 'fileutils'
|
|
|
|
|
2010-11-11 11:54:51 +00:00
|
|
|
class Noprocrast
|
2010-11-10 15:08:57 +00:00
|
|
|
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!
|
2010-11-30 01:22:33 +00:00
|
|
|
hosts = File.read(deny_file_path).split(/\n/).select { |line| line.match(/[a-zA-Z0-9]/) }.map(&:strip)
|
|
|
|
wwwhosts = hosts.map { |h| "www." + h.to_s unless h =~ /^www/ }
|
|
|
|
(hosts + wwwhosts).sort
|
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|
|
2010-11-11 11:54:51 +00:00
|
|
|
file << "\n\n# noprocrast start\n#{current_hosts.map { |host| "127.0.0.1 #{host}" }.join("\n")}\n# noprocrast end"
|
2010-11-10 15:08:57 +00:00
|
|
|
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!
|
2010-11-11 11:54:51 +00:00
|
|
|
clean_hosts = hosts_file_content.gsub(/(\n\n)?\# noprocrast start.*\# noprocrast end/m, '')
|
2010-11-10 15:08:57 +00:00
|
|
|
File.open("/etc/hosts", 'w') do |file|
|
|
|
|
file << clean_hosts
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def active?
|
2010-11-11 11:54:51 +00:00
|
|
|
hosts_file_content.match(/\# noprocrast start/)
|
2010-11-10 15:08:57 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def status_message
|
2010-11-11 11:54:51 +00:00
|
|
|
active? ? "noprocrast enabled for #{current_hosts.size} hosts" : "noprocrast disabled"
|
2010-11-10 15:08:57 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def backup_hosts_file_if_required!
|
2010-11-11 11:54:51 +00:00
|
|
|
unless File.exists?("/etc/.hosts.noprocrastbackup")
|
|
|
|
FileUtils.cp("/etc/hosts", "/etc/.hosts.noprocrastbackup")
|
2010-11-10 15:08:57 +00:00
|
|
|
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
|
|
|
|
|