Module: Familia::Features::Quantization::ClassMethods

Included in:
Familia::Features::Quantization
Defined in:
lib/familia/features/quantization.rb

Instance Method Summary collapse

Instance Method Details

#qstamp(quantum = nil, pattern: nil, time: nil) ⇒ Integer, String

Generates a quantized timestamp based on the given parameters.

This method rounds the current time to the nearest quantum and optionally formats it according to the given pattern. It’s useful for creating time-based buckets or keys with reduced granularity.

Examples:

User.qstamp(1.hour, '%Y%m%d%H')  # Returns a string like "2023060114" for 2:30 PM
User.qstamp(10.minutes)  # Returns an integer timestamp rounded to the nearest 10 minutes
User.qstamp([1.hour, '%Y%m%d%H'])  # Same as the first example

Parameters:

  • quantum (Integer, Array, nil) (defaults to: nil)

    The time quantum in seconds or an array of [quantum, pattern].

  • pattern (String, nil) (defaults to: nil)

    The strftime pattern to format the timestamp.

  • now (Time, nil)

    The current time (default: Familia.now).

Returns:

  • (Integer, String)

    A unix timestamp or formatted timestamp string.

Raises:

  • (ArgumentError)

    If quantum is not positive



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/familia/features/quantization.rb', line 26

def qstamp(quantum = nil, pattern: nil, time: nil)
  # Handle default values and array input
  if quantum.is_a?(Array)
    quantum, pattern = quantum
  end
  quantum ||= @opts[:quantize] || ttl || 10.minutes

  # Validate quantum
  unless quantum.is_a?(Numeric) && quantum.positive?
    raise ArgumentError, "Quantum must be positive (#{quantum.inspect} given)"
  end

  # Call Familia.qstamp with our processed parameters
  Familia.qstamp(quantum, pattern: pattern, time: time)
end