Class: SubtitleIt::Subtime

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/subtitle_it/subtime.rb

Overview

A kinda of Time

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Subtime

Returns a new instance of Subtime.



8
9
10
11
# File 'lib/subtitle_it/subtime.rb', line 8

def initialize(data)
  fail if data.nil?
  parse_data(data)
end

Instance Attribute Details

#hrsObject

Returns the value of attribute hrs.



6
7
8
# File 'lib/subtitle_it/subtime.rb', line 6

def hrs
  @hrs
end

#minObject

Returns the value of attribute min.



6
7
8
# File 'lib/subtitle_it/subtime.rb', line 6

def min
  @min
end

#msObject

Returns the value of attribute ms.



6
7
8
# File 'lib/subtitle_it/subtime.rb', line 6

def ms
  @ms
end

#secObject

Returns the value of attribute sec.



6
7
8
# File 'lib/subtitle_it/subtime.rb', line 6

def sec
  @sec
end

Instance Method Details

#+(other) ⇒ Object



41
42
43
# File 'lib/subtitle_it/subtime.rb', line 41

def +(other)
  Subtime.new(to_i + other.to_i)
end

#-(other) ⇒ Object



45
46
47
# File 'lib/subtitle_it/subtime.rb', line 45

def -(other)
  Subtime.new(to_i - other.to_i)
end

#<=>(other) ⇒ Object



49
50
51
# File 'lib/subtitle_it/subtime.rb', line 49

def <=>(other)
  to_i <=> other.to_i
end

#parse_data(data) ⇒ Object

parses string like ‘00:00:00,000’ or single number as ms.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/subtitle_it/subtime.rb', line 14

def parse_data(data)
  case data
  when Numeric
    @sec, @ms  = data.divmod(1000)
    @min, @sec = @sec.divmod(60)
    @hrs, @min = @min.divmod(60)
  when String
    time, float = data.split(/\.|\,/)
    time = time.split(/:/).map(&:to_i)
    @ms =  (('0.%d' % float.to_i).to_f * 1000).to_i if float
    @sec, @min, @hrs = time.reverse
  else fail 'Format unknown.'
  end
  # FIXME: dunno what to do about this.. nil = problems with to_i
  @hrs ||= 0; @min ||= 0; @sec ||= 0;  @ms ||= 0
end

#to_iObject

return time as a total in ms



37
38
39
# File 'lib/subtitle_it/subtime.rb', line 37

def to_i
  (@hrs * 3600 + @min * 60 + @sec) * 1000 + @ms
end

#to_s(sep = '.') ⇒ Object

to_s(separator) => to_s(“,”) => 00:00:00,000



32
33
34
# File 'lib/subtitle_it/subtime.rb', line 32

def to_s(sep = '.')
  "%02d:%02d:%02d#{sep}%03d" % [@hrs, @min, @sec,  @ms]
end