Module: Familia::Refinements::TimeLiterals

Defined in:
lib/familia/refinements/time_literals.rb

Overview

Note:

to_bytes also lives here until we find it a better home!

Familia::Refinements::TimeLiterals

This module provides a set of refinements for Numeric and String to enable readable and expressive time duration and timestamp manipulation.

The name "TimeLiterals" reflects its core purpose: to allow us to treat numeric values directly as "literals" of time units (e.g., 5.minutes, 1.day). It extends this concept to include conversions between these literal time quantities, parsing string representations of time durations, and performing common timestamp-based calculations in an intuitive manner.

Examples:

Expressing durations

5.minutes.ago           #=> A Time object 5 minutes in the past
1.day.from_now          #=> A Time object 1 day in the future
(2.5).hours             #=> 9000.0 (seconds)

Converting between units

3600.in_hours           #=> 1.0
86400.in_days           #=> 1.0

Parsing string durations

"30m".in_seconds        #=> 1800.0
"2.5h".in_seconds       #=> 9000.0

Timestamp calculations

timestamp = 2.days.ago.to_i
timestamp.days_old      #=> ~2.0
timestamp.older_than?(1.day) #=> true

Defined Under Namespace

Modules: NumericMethods, StringMethods

Constant Summary collapse

PER_MICROSECOND =

Time unit constants

0.000001
PER_MILLISECOND =
0.001
PER_MINUTE =
60.0
PER_HOUR =
3600.0
PER_DAY =
86_400.0
PER_WEEK =
604_800.0
PER_YEAR =

365.2425 days (Gregorian year)

31_556_952.0
PER_MONTH =

30.437 days (consistent with Gregorian year)

PER_YEAR / 12.0
UNIT_METHODS =
{
  'y' => :years,
  'year' => :years,
  'years' => :years,
  'mo' => :months,
  'month' => :months,
  'months' => :months,
  'w' => :weeks,
  'week' => :weeks,
  'weeks' => :weeks,
  'd' => :days,
  'day' => :days,
  'days' => :days,
  'h' => :hours,
  'hour' => :hours,
  'hours' => :hours,
  'm' => :minutes,
  'minute' => :minutes,
  'minutes' => :minutes,
  'ms' => :milliseconds,
  'millisecond' => :milliseconds,
  'milliseconds' => :milliseconds,
  'us' => :microseconds,
  'microsecond' => :microseconds,
  'microseconds' => :microseconds,
  'μs' => :microseconds,
}.freeze

Class Method Summary collapse

Class Method Details

.convert_to_seconds(value, unit) ⇒ Object

Shared conversion logic



79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/familia/refinements/time_literals.rb', line 79

def self.convert_to_seconds(value, unit)
  case UNIT_METHODS.fetch(unit.to_s.downcase, nil)
  when :milliseconds then value * PER_MILLISECOND
  when :microseconds then value * PER_MICROSECOND
  when :minutes then value * PER_MINUTE
  when :hours then value * PER_HOUR
  when :days then value * PER_DAY
  when :weeks then value * PER_WEEK
  when :months then value * PER_MONTH
  when :years then value * PER_YEAR
  else value
  end
end