Skip to content

Instantly share code, notes, and snippets.

@JamesRyanATX
Created May 16, 2011 21:10
Show Gist options
  • Save JamesRyanATX/975381 to your computer and use it in GitHub Desktop.
Save JamesRyanATX/975381 to your computer and use it in GitHub Desktop.
Blacklist distracting websites while working
#!/opt/local/bin/ruby
#
# iam - block distracting websites while working
#
# Examples:
#
# Switch to work mode -- disable distracting websites
# % iam working
#
# Switch to play mode -- enable distracting websites
# % iam playing
#
# Block some distracting sites
# % iam add facebook.com
# % iam add reddit.com
#
# Unblock something:
# % iam remove reddit.com
#
# List database
# % iam list
# facebook.com
#
# Find out which mode you're in
# % iam
# playing
#
#
# Notes:
# 1. /etc/hosts must be writable by you
# 2. iam creates two hidden files-- ~/.iam and ~/.iamdb to store the mode and database, respectively
#
# Files we need
MODE_FILE = ENV['HOME'] + '/.iam'
DATABASE_FILE = ENV['HOME'] + '/.iamdb'
HOSTS_FILE = '/etc/hosts'
# Default to playing with empty blacklist
database = [ ]
hosts = [ ]
mode = 'playing'
File.open(DATABASE_FILE, 'r').each { |host| database << host.strip } if File.exists? DATABASE_FILE
File.open(MODE_FILE, 'r').each { |line| mode = line.strip } if File.exists? MODE_FILE
File.open(HOSTS_FILE, 'r').each { |line| hosts << line.strip }
hosts.delete_if { |line| line.match(/\#iam$/) }
# Do stuff
case ARGV[0]
when 'working', 'playing'
mode = ARGV[0]
when 'list'
puts database.join "\n"
when 'add'
database << ARGV[1]
when 'remove'
database.delete_if { |h| h == ARGV[1] }
else
puts mode
end
# Clean up database
database.delete_if { |h| h.nil? || h.length == 0 }
# Build working database
if mode == 'working'
hosts = hosts + database.map { |h| "127.0.0.1\t#{h} #iam" }
end
# Write working DB
File.open(DATABASE_FILE, 'w+') { |f| f.write database.join "\n" }
# Write mode
File.open(MODE_FILE, 'w+') { |f| f.write mode }
# Write hosts file
File.open(HOSTS_FILE, "w") { |f| f.write hosts.join "\n" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment