lib/time/task_timer.rb in bblib-0.2.2 vs lib/time/task_timer.rb in bblib-0.3.0
- old
+ new
@@ -1,20 +1,11 @@
module BBLib
- class TaskTimer
- attr_reader :tasks, :save, :retention
+ class TaskTimer < LazyClass
+ attr_hash :tasks, default: Hash.new
+ attr_int_between -1, nil, :retention, default: 100
- def initialize task:nil, retention:100
- @tasks = {}
- self.retention = retention
- if task then start task end
- end
-
- def retention= num
- @retention = num.nil? ? nil : BBLib.keep_between(num, -1, nil)
- end
-
def time task = :default, type = :current
return nil unless @tasks.keys.include? task
numbers = @tasks[task][:history].map{ |v| v[:time] }
case type
when :current
@@ -63,39 +54,54 @@
def restart task = :default
start(task) unless stop(task).nil?
end
- def save= save
- @save = save
- end
-
def active? task
return false unless @tasks.keys.include? task
!@tasks[task][:current].nil?
end
- def method_missing *args
- temp = args.first.to_s.sub('p_','').to_sym
+ def stats task, pretty: false
+ return nil unless @tasks.include?(task)
+ stats = "#{task}" + "\n" + '-'*30 + "\n"
+ TIMER_TYPES.each do |k,v|
+ next if STATS_IGNORE.include?(k)
+ stats+= k.to_s.capitalize.ljust(10) + "#{self.send(k, task, pretty:pretty)}\n"
+ end
+ stats
+ end
+
+ def method_missing *args, **named
+ temp = args.first.to_sym
+ pretty = named.delete :pretty
type, task = TIMER_TYPES.keys.find{ |k| k == temp || TIMER_TYPES[k].include?(temp) }, args[1] ||= :default
- raise NoMethodError unless type
+ return super unless type
t = time task, type
- args.first.to_s.start_with?('p_') && type != :count ? t.to_duration : t
+ pretty && type != :count && t ? (t.is_a?(Array) ? t.map{|m| m.to_duration} : t.to_duration) : t
end
private
+ STATS_IGNORE = [:current, :all]
+
TIMER_TYPES = {
current: [],
- avg: [:average, :av],
- all: [:times],
- max: [:maximum, :largest],
- min: [:minimum, :smallest],
- sum: [],
- last: [:latest],
- first: [:initial],
- count: [:total]
+ count: [:total],
+ first: [:initial],
+ last: [:latest],
+ min: [:minimum, :smallest],
+ max: [:maximum, :largest],
+ avg: [:average, :av],
+ sum: [],
+ all: [:times]
}
+
+ def lazy_init *args
+ if args.first.is_a?(Symbol)
+ start(args.first)
+ end
+ end
end
end