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
29
30
# File 'lib/subunit.rb', line 9

def initialize(raw_units={}, obj)
  
  @debug = false
  
  @raw_units = raw_units
  
  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

#strfunit(s) ⇒ Object

usage: Subunit.new(units=hours:60, seconds: 661)\

.strfunit("%x") #=> 11m 1s

%x e.g. 11m 1s %X e.g. 11 minutes 1 second %c e.g. 00:11:01



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
67
# File 'lib/subunit.rb', line 39

def strfunit(s)    
  
  s.sub!('%x') do |x|
    to_h.map {|label, val| val.to_s + label[0]}.join(' ')
  end
  
  s.sub!('%X') do |x|
    
    to_h.map do |label, val| 
      
      next if val == 0
      label2 = val > 1 ? label.to_s : label.to_s.sub(/s$/,'')
      val.to_s + ' ' + label2
      
    end.compact.join(' ')
    
  end    
  
  s.sub!('%c') do |x|
    
    a = @raw_units.values.reverse
    a << a[-1]
    
    fmt = a.map {|v| "%0" + v.to_s.length.to_s + "d"}.join(":")
    fmt % to_a
  end    

  s
end

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



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/subunit.rb', line 69

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