Class: TwitterCldr::Formatters::TimespanFormatter

Inherits:
Base
  • Object
show all
Defined in:
lib/twitter_cldr/formatters/calendars/timespan_formatter.rb

Constant Summary collapse

TIME_IN_SECONDS =
{ 
  :second => 1,
  :minute => 60,
  :hour => 3600,
  :day => 86400,
  :week => 604800,
  :month => 2629743.83,
  :year => 31556926 
}

Instance Attribute Summary

Attributes inherited from Base

#tokenizer

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ TimespanFormatter

Returns a new instance of TimespanFormatter.


19
20
21
# File 'lib/twitter_cldr/formatters/calendars/timespan_formatter.rb', line 19

def initialize(options = {})
  @tokenizer = TwitterCldr::Tokenizers::TimespanTokenizer.new(:locale => extract_locale(options))
end

Instance Method Details

#calculate_time(seconds, unit) ⇒ Object

0 <-> 29 secs # => seconds 30 secs <-> 44 mins, 29 secs # => minutes 44 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => hours 23 hrs, 59 mins, 29 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => days 29 days, 23 hrs, 59 mins, 29 secs <-> 1 yr minus 1 sec # => months 1 yr <-> max time or date # => years


61
62
63
# File 'lib/twitter_cldr/formatters/calendars/timespan_formatter.rb', line 61

def calculate_time(seconds, unit)
  (seconds / TIME_IN_SECONDS[unit]).round.to_i
end

#calculate_unit(seconds) ⇒ Object


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/twitter_cldr/formatters/calendars/timespan_formatter.rb', line 37

def calculate_unit(seconds)
  if seconds < 30
    :second
  elsif seconds < 2670
    :minute
  elsif seconds < 86369
    :hour
  elsif seconds < 604800
    :day
  elsif seconds < 2591969
    :week
  elsif seconds < 31556926
    :month
  else
    :year
  end
end

#format(seconds, unit) ⇒ Object


23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/twitter_cldr/formatters/calendars/timespan_formatter.rb', line 23

def format(seconds, unit)
  direction = seconds < 0 ? :ago : :until

  if unit.nil? || unit == :default
    unit = self.calculate_unit(seconds.abs)
  end

  number = calculate_time(seconds.abs, unit)

  tokens = @tokenizer.tokens(:direction => direction, :unit => unit, :number => number)
  strings = tokens.map { |token| token[:value]}
  strings.join.gsub(/\{[0-9]\}/, number.to_s)
end