Skip to content

Instantly share code, notes, and snippets.

@dbalatero
Last active August 23, 2022 15:48
Show Gist options
  • Save dbalatero/6443380 to your computer and use it in GitHub Desktop.
Save dbalatero/6443380 to your computer and use it in GitHub Desktop.
Records how long you practice something (guitar, language, etc) each day, and displays it.
#!/usr/bin/env ruby
class Practice
def initialize
@data = {}
try_to_load_data
end
def record_today(minutes)
@data[key_for(Time.now)] = minutes
end
def write_data_to_file!
File.open(data_file, 'w') do |f|
@data.keys.sort.each do |key|
f.write("#{key}|#{@data[key]}\n")
end
end
end
def data_points
today = Time.now
points = [minutes_for(today)]
1.upto(days_to_show - 1) do |offset|
points.unshift(minutes_for(today - (offset * 86400)))
end
points
end
private
def minutes_for(date)
@data[key_for(date)] || 0
end
def days_to_show
(ENV['PRACTICE_DAYS'] || 14).to_i
end
def data_file
ENV['PRACTICE_DATA'] || "#{ENV['HOME']}/.practice"
end
def key_for(date)
date.strftime(date_format)
end
def date_format
"%d-%m-%Y" # 31-02-2013
end
def try_to_load_data
return unless File.exist?(data_file)
File.open(data_file, 'r').each_line do |line|
date, minutes = line.split('|')
@data[date] = minutes.to_i
end
end
end
practice = Practice.new
if ARGV.empty?
puts practice.data_points.join(' ')
else
case ARGV.first
when 'record'
minutes = ARGV[1].to_i
practice.record_today(minutes)
practice.write_data_to_file!
puts "Recorded #{minutes} minutes for today."
end
end
# records 120 minutes for today
$ practice record 120
# shows last 14 days
$ practice | spark
▁▁▁▁▁▁▁▁▁▁▁▁▆█
# shows last 3 days
$ PRACTICE_DAYS=3 practice | spark
# reads/writes to different data file
$ PRACTICE_DATA=/tmp/datafile.txt practice
@usonianhorizon
Copy link

usonianhorizon commented Dec 3, 2021

This is such a simple and elegant script to help with habit tracking.

I have one small suggestion: on my local copy I have changed line 10 from:

@data[key_for(Time.now)] = minutes

to:

@data[key_for(Time.now)] += minutes

so that when I enter in a value several times throughout the day, the sum is used rather than the original value being overwritten.

Regards.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment