class Luxafor::Toggl::State

Constants

DEFAULT_TIME

Public Class Methods

coerce_as_of(value) click to toggle source
# File lib/luxafor/toggl/state.rb, line 15
def self.coerce_as_of(value)
  return value if value.is_a? DateTime

  DateTime.parse(value)
end
coerce_state(value) click to toggle source
# File lib/luxafor/toggl/state.rb, line 11
def self.coerce_state(value)
  value.to_sym
end
new_from_task(task) click to toggle source
# File lib/luxafor/toggl/state.rb, line 21
def self.new_from_task(task)
  instance = allocate

  instance.initialize_from_task(task)
  instance
end

Public Instance Methods

colour() click to toggle source
# File lib/luxafor/toggl/state.rb, line 39
def colour
  case state
  when :idle
    '000000'
  when :busy
    'FF0000'
  when :available
    '00FF00'
  end
end
initialize_from_task(task) click to toggle source
# File lib/luxafor/toggl/state.rb, line 28
def initialize_from_task(task)
  @state = determine_state_from_task(task)
  @as_of = determine_as_of_from_task(task)
end
store!(destination) click to toggle source
# File lib/luxafor/toggl/state.rb, line 50
def store!(destination)
  data = {
    'state' => state,
    'as_of' => as_of.to_s,
  }

  File.unlink(destination) if File.exist?(destination)

  File.open(destination, 'w') do |f|
    f.write(Oj.dump(data))
  end
end
sufficiently_different_from?(other_state) click to toggle source
# File lib/luxafor/toggl/state.rb, line 33
def sufficiently_different_from?(other_state)
  return true if @state != other_state.state

  false
end

Private Instance Methods

determine_as_of_from_task(task) click to toggle source
# File lib/luxafor/toggl/state.rb, line 75
def determine_as_of_from_task(task)
  state = determine_state_from_task(task)

  if state == :busy
    DateTime.parse(task['start'])
  elsif state == :available
    DateTime.parse(task['stop'])
  elsif state == :idle
    return DEFAULT_TIME if task.nil?

    DateTime.parse(task['stop'])
  else
    raise "Cannot determine as_of from task in state #{state}: #{task}"
  end
end
determine_state_from_task(task) click to toggle source
# File lib/luxafor/toggl/state.rb, line 65
def determine_state_from_task(task)
  return :idle if     task.nil?        # There is no latest task at all...
  return :busy unless task.key? 'stop' # There's a task with no stop time, still in progress.

  now        = DateTime.now.to_time.to_i
  stopped_at = DateTime.parse(task['stop']).to_time.to_i

  (now - stopped_at) >= Luxafor::Toggl.idle_time ? :idle : :available
end