Class: Timefly

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

Constant Summary collapse

TIME_UNIT_MAPPER =
{
  second: { short: 's', full: 'second' },
  minute: { short: 'm', full: 'minute' },
  hour: { short: 'h', full: 'hour' },
  day: { short: 'd', full: 'day' },
  week: { short: 'w', full: 'week' },
  month: { short: 'mo', full: 'month' },
  year: { short: 'y', full: 'year' },
}
DEFAULT_FORMAT =
'%n %U ago'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(origin_time) ⇒ Timefly

initialize with either String, Time or Date instance Arguments:

origin_time: (String/Time/Date)


20
21
22
23
# File 'lib/timefly.rb', line 20

def initialize(origin_time)
  self.origin_time = origin_time
  process
end

Instance Attribute Details

#origin_timeObject

Returns the value of attribute origin_time.



3
4
5
# File 'lib/timefly.rb', line 3

def origin_time
  @origin_time
end

Instance Method Details

#age(options = {}) ⇒ Object

returns the age in years from the date of birth

Example:

>> dob = Time.new(1987,8,2)
>> Timefly.new(dob).age
=> 27
>> Timefly.new('1987.08.02').age # dob can be of format YYYY.MM.DD, YYYY-MM-DD and YYYY/MM/DD
=> 27
>> Timefly.new('1987.08.02').age({ format: '%y years, %m months' })
=> 27 years, 10 months

Arguments:

options: (Hash) { format  :(String) }
                          eg, '%y years, %m months'. %y will give years, and %m will give months


39
40
41
42
43
44
45
46
47
# File 'lib/timefly.rb', line 39

def age(options = {})
  if options[:format].nil?
    years_from_origin_time
  else
    options[:format]
      .gsub(/\%y/, years_from_origin_time.to_s)
      .gsub(/\%m/, months_diff_from_origin_time_month.to_s)
  end
end

#elapsed_time(options = {}) ⇒ Object

returns the time elapsed in a readable format

Example:

>> Timefly.new(origin_time).time_elapsed
=> '4 hours ago'


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/timefly.rb', line 54

def elapsed_time(options = {})
  if time_elapsed_in_seconds?
    elapsed_time_in_seconds(options)
  elsif time_elapsed_in_minutes?
    elapsed_time_in_minutes(options)
  elsif time_elapsed_in_hours?
    elapsed_time_in_hours(options)
  elsif time_elapsed_in_days?
    elapsed_time_in_days(options)
  elsif time_elapsed_in_weeks?
    elapsed_time_in_weeks(options)
  elsif time_elapsed_in_months?
    elapsed_time_in_months(options)
  else
    elapsed_time_in_years(options)
  end
end