time_sentence 0.0.3 → 0.0.4

Sign up to get free protection for your applications and to get access to all the features.
File without changes
@@ -1,10 +1,29 @@
1
1
  class Time
2
+
3
+ # Converts number of seconds to human-readable sentences.
4
+ #
5
+ # == Examples
6
+ #
7
+ # Time.sentence(1.hour) #=> "1 hour"
8
+ # Time.sentence(168.hours) #=> "1 week"
9
+ # Time.sentence(9999.seconds) #=> "2 hours, 46 minutes, 39 seconds"
10
+ # Time.sentence(123456876543.seconds) #=> "4 millennia, 25 decades, 2 years"
11
+ #
12
+ # == Params
13
+ #
14
+ # @param [Numeric] Number of seconds to convert to a sentence
15
+ # @param [Integer] Specificity of the sentence (how many clauses are included)
16
+ # @return [String] Generated sentence
2
17
  def self.sentence seconds, specificity = 3
3
18
 
4
19
  return 'now' if seconds == 0
5
20
 
21
+ # if seconds is negative, then the time is in the past so later
22
+ # on we'll append "ago" to the return string
6
23
  ago = seconds < 0
7
24
 
25
+ # Tracks what the values and names of each unit, as well as the
26
+ # conversion factor needed to go to the next larger unit
8
27
  time = [
9
28
  { value: seconds.abs, unit: 'second', conversion: 60 },
10
29
  { value: 0, unit: 'minute', conversion: 60 },
@@ -17,15 +36,21 @@ class Time
17
36
  { value: 0, unit: 'millennium', conversion: nil },
18
37
  ]
19
38
 
39
+ # divmod returns both the result of a division and the remainder,
40
+ # which is exactly what we need eg:
41
+ # minutes, seconds = seconds.divmod 60
20
42
  time.each_cons(2) do |this_time, next_time|
21
43
  next_time[:value], this_time[:value] = this_time[:value].divmod this_time[:conversion]
22
44
  end
23
45
 
46
+ # remove any elements that are 0, because we don't need them for the sentence
24
47
  time = time.delete_if { |t| t[:value] == 0 }
25
48
 
49
+ # starting with the largest unit first, build the sentence elements
26
50
  out = []
27
51
  time.reverse.each do |t|
28
52
  out << "#{t[:value]} #{t[:unit].pluralize t[:value]}"
53
+ # if we now have the right number of elements, then break
29
54
  break if out.count == specificity
30
55
  end
31
56
 
@@ -1,3 +1,3 @@
1
1
  module TimeSentence
2
- VERSION = '0.0.3'
2
+ VERSION = '0.0.4'
3
3
  end
data/lib/time_sentence.rb CHANGED
@@ -1,4 +1,4 @@
1
1
  require 'time_sentence/version'
2
2
 
3
- require 'ext/time'
4
- require 'ext/numeric'
3
+ require 'ext/ts_time'
4
+ require 'ext/ts_numeric'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: time_sentence
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.3
4
+ version: 0.0.4
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors:
@@ -87,8 +87,8 @@ files:
87
87
  - Gemfile
88
88
  - Rakefile
89
89
  - Readme.md
90
- - lib/ext/numeric.rb
91
- - lib/ext/time.rb
90
+ - lib/ext/ts_numeric.rb
91
+ - lib/ext/ts_time.rb
92
92
  - lib/time_sentence.rb
93
93
  - lib/time_sentence/version.rb
94
94
  - spec/spec_helper.rb