Created
August 8, 2013 09:05
-
-
Save olivernn/6182988 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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