Skip to content

Instantly share code, notes, and snippets.

@olivernn
Created August 8, 2013 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olivernn/6182988 to your computer and use it in GitHub Desktop.
Save olivernn/6182988 to your computer and use it in GitHub Desktop.
class Duration
include Comparable
attr_reader :milliseconds
def initialize(value = 0)
case value
when Fixnum
@milliseconds = value
when String
minutes, seconds = value.split(':').map(&:to_f)
if seconds.nil?
@milliseconds = minutes * 1000
else
@milliseconds = (minutes * 60 * 1000 + seconds * 1000).to_i
end
else
raise ArgumentError
end
end
def to_i
milliseconds
end
def to_s
seconds_string = sprintf('%.3f', seconds)
if over_a_minute?
"#{minutes}:#{seconds_string.rjust(6, '0')}"
else
seconds_string
end
end
def <=>(other)
milliseconds <=> other.milliseconds
end
private
def seconds
if over_a_minute?
(milliseconds - 60_000).to_f / 1_000
else
milliseconds.to_f / 1_000
end
end
def minutes
if over_a_minute?
milliseconds / 60_000
end
end
def over_a_minute?
milliseconds > 60_000
end
end
require 'active_support/concern'
module Timeable
extend ActiveSupport::Concern
included do
composed_of :duration,
mapping: %i(milliseconds),
converter: :new
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment