Class: HumanDate::DateTranslator
- Inherits:
-
Object
- Object
- HumanDate::DateTranslator
- Defined in:
- lib/human-date/date_translator.rb
Constant Summary collapse
- TIME =
{ :year => 365 * 24 * 60 * 60, :month => 30 * 24 * 60 * 60, :day => 24 * 60 * 60, :hour => 60 * 60, :minute => 60, :second => 1 }
Instance Attribute Summary collapse
-
#parts ⇒ Object
Returns the value of attribute parts.
-
#tolerance ⇒ Object
Returns the value of attribute tolerance.
Instance Method Summary collapse
-
#initialize ⇒ DateTranslator
constructor
A new instance of DateTranslator.
- #translate(from, to) ⇒ Object
Constructor Details
#initialize ⇒ DateTranslator
Returns a new instance of DateTranslator.
16 17 18 19 |
# File 'lib/human-date/date_translator.rb', line 16 def initialize @tolerance = 1 @parts = TIME.keys end |
Instance Attribute Details
#parts ⇒ Object
Returns the value of attribute parts.
5 6 7 |
# File 'lib/human-date/date_translator.rb', line 5 def parts @parts end |
#tolerance ⇒ Object
Returns the value of attribute tolerance.
5 6 7 |
# File 'lib/human-date/date_translator.rb', line 5 def tolerance @tolerance end |
Instance Method Details
#translate(from, to) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/human-date/date_translator.rb', line 21 def translate from, to total_difference_in_seconds = ((to-from) * 60 * 60 * 24).to_i absolute_total_difference_in_seconds = total_difference_in_seconds.abs return 'now' if absolute_total_difference_in_seconds <= tolerance words = [] parts.each do |key| if absolute_total_difference_in_seconds >= TIME[key] count = 0 while absolute_total_difference_in_seconds >= TIME[key] absolute_total_difference_in_seconds -= TIME[key] count += 1 end word = "#{count} #{key}" word += 's' if count >= 2 words << word end end sentence = join_words(words) sentence += ' ago' if total_difference_in_seconds < 0 sentence end |