Class: Noprocrast

Inherits:
Object
  • Object
show all
Defined in:
lib/noprocrast.rb

Class Method Summary collapse

Class Method Details

.activate!Object



22
23
24
25
26
27
28
29
# File 'lib/noprocrast.rb', line 22

def activate!
	backup_hosts_file_if_required!
	deactivate!   # ensure that /etc/hosts is clean
	File.open("/etc/hosts", 'a') do |file|
		file << "\n\n# noprocrast start\n#{current_hosts.map { |host| "127.0.0.1 #{host}" }.join("\n")}\n# noprocrast end"
	end
	system "dscacheutil -flushcache" # only for OSX >= 10.5: flush the DNS cache
end

.active?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/noprocrast.rb', line 38

def active?
	hosts_file_content.match(/\# noprocrast start/)
end

.backup_hosts_file_if_required!Object



46
47
48
49
50
# File 'lib/noprocrast.rb', line 46

def backup_hosts_file_if_required!
	unless File.exists?("/etc/.hosts.noprocrastbackup")
		FileUtils.cp("/etc/hosts", "/etc/.hosts.noprocrastbackup")
	end
end

.current_hostsObject



13
14
15
16
# File 'lib/noprocrast.rb', line 13

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)
end

.deactivate!Object



31
32
33
34
35
36
# File 'lib/noprocrast.rb', line 31

def deactivate!
	clean_hosts = hosts_file_content.gsub(/(\n\n)?\# noprocrast start.*\# noprocrast end/m, '')
	File.open("/etc/hosts", 'w') do |file|
		file << clean_hosts
	end	
end

.default_hostsObject



5
6
7
# File 'lib/noprocrast.rb', line 5

def default_hosts
	['news.ycombinator.com', 'twitter.com', 'facebook.com', 'reddit.com']
end

.deny_file_pathObject



9
10
11
# File 'lib/noprocrast.rb', line 9

def deny_file_path
	File.expand_path("~/.noprocast")
end

.edit!Object



60
61
62
63
64
# File 'lib/noprocrast.rb', line 60

def edit!
	setup_deny_file_if_required!
	editor = ENV['EDITOR'] || 'vi'
	system "#{editor} #{deny_file_path}"
end

.hosts_file_contentObject



18
19
20
# File 'lib/noprocrast.rb', line 18

def hosts_file_content
	File.read("/etc/hosts")
end

.setup_deny_file_if_required!Object



52
53
54
55
56
57
58
# File 'lib/noprocrast.rb', line 52

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

.status_messageObject



42
43
44
# File 'lib/noprocrast.rb', line 42

def status_message
	active? ? "noprocrast enabled for #{current_hosts.size} hosts" : "noprocrast disabled"
end