Class: Subunit

Inherits:
Object
  • Object
show all
Defined in:
lib/subunit.rb

Overview

file: subunit.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw_units = {}, obj) ⇒ Subunit

Returns a new instance of Subunit.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/subunit.rb', line 9

def initialize(raw_units={}, obj)
  
  @debug = false
  
  if obj.is_a? Array then
    
    a = obj[0..-2]
    len = raw_units.to_a.length
    val = ([0]*(len-1) + a).slice(-(len), len).zip(raw_units.values)\
        .inject(0) {|r,x| r + x.inject(:*) }
    @to_i = val + obj[-1]
    
  else
    
    raw_subunit = obj || 0
    method((raw_units.class.to_s.downcase + '_units').to_sym)\
        .call(raw_units, raw_subunit)
    
  end
end

Instance Attribute Details

#to_aObject (readonly)

Returns the value of attribute to_a.



7
8
9
# File 'lib/subunit.rb', line 7

def to_a
  @to_a
end

#to_hObject (readonly)

Returns the value of attribute to_h.



7
8
9
# File 'lib/subunit.rb', line 7

def to_h
  @to_h
end

#to_iObject (readonly)

Returns the value of attribute to_i.



7
8
9
# File 'lib/subunit.rb', line 7

def to_i
  @to_i
end

Instance Method Details

#to_s(omit: [], verbose: true) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/subunit.rb', line 30

def to_s(omit: [], verbose: true)
  
  if not verbose then
    
    r =  self.to_a.reverse.take_while {|x| x > 0}.reverse\
        .map {|x| "%02d" % x}.join(':')
    
    if r.length < 2 then
      return '00:00'
    elsif r.length == 2      
      return '00:' + r
    else
      return r
    end
    
  end
  
  h = @to_h
  omit.each {|x| h.delete x}

  list = h.to_a
  n = list.find {|_,v| v > 0 }
  a = list[list.index(n)..-1].map {|x|"%d %s" % x.reverse}        
      
  duration = case a.length

  when 1
    a.first  
  when 2
    a.join ' and '
  else                   
    "%s and %s" % [a[0..-2].join(', '), a[-1]]
  end
  
  duration.gsub(/(\b1 \w+)s/, '\1')

end