Class: NaturalTime

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

Constant Summary collapse

UNITS_OF_TIME =
[["year", "years"], ["month", "months"], ["week", "weeks"], ["day", "days"], ["hour", "hours"], ["minute", "minutes"]]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(duration_in_seconds, options = {}) ⇒ NaturalTime

Returns a new instance of NaturalTime.



10
11
12
13
14
15
16
# File 'lib/natural_time.rb', line 10

def initialize(duration_in_seconds, options={})
  @precision = options[:precision]
  duration_in_seconds = duration_in_seconds.to_i
  @past = duration_in_seconds < 1
  @duration = duration_in_seconds.abs
  elapsed_time = elapsed_time(duration_in_seconds)
end

Instance Attribute Details

#durationObject

Returns the value of attribute duration.



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

def duration
  @duration
end

#pastObject

Returns the value of attribute past.



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

def past
  @past
end

#precisionObject

Returns the value of attribute precision.



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

def precision
  @precision
end

Instance Method Details

#distanceObject



38
39
40
41
42
43
44
45
# File 'lib/natural_time.rb', line 38

def distance
  if past
    modifier = "ago"
  else
    modifier = "from now"
  end
  "#{to_sentence} #{modifier}"
end

#elapsed_time(duration_in_seconds) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/natural_time.rb', line 47

def elapsed_time(duration_in_seconds)
  return "0 seconds" if duration_in_seconds <= 0

  elapsed_time = []

  seconds_left = duration_in_seconds
  
  UNITS_OF_TIME.each do |period|
    amount = (seconds_left / 1.send(period.first)).to_i
    str = amount == 1 ? period[0] : period[1]
    elapsed_time << "#{amount} #{str}" if amount > 0
    seconds_left = seconds_left % 1.send(period.first)
  end
  
  seconds = seconds_left % 1.minute
  str = seconds == 1 ? "second" : "seconds"
  elapsed_time << "#{seconds.to_i} #{str}" unless (seconds == 0 && elapsed_time.compact.length > 0)    
  
  if precision
    elapsed_time.compact.first(precision)
  else
    elapsed_time.compact
  end
end

#natural_timeObject



22
23
24
# File 'lib/natural_time.rb', line 22

def natural_time
  to_array.join(", ")
end

#to_aObject



30
31
32
# File 'lib/natural_time.rb', line 30

def to_a
  [elapsed_time(duration)].flatten
end

#to_arrayObject



34
35
36
# File 'lib/natural_time.rb', line 34

def to_array
  to_a
end

#to_sObject



26
27
28
# File 'lib/natural_time.rb', line 26

def to_s
  natural_time
end

#to_sentenceObject



18
19
20
# File 'lib/natural_time.rb', line 18

def to_sentence
  to_array.to_sentence
end