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



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/familia/features/quantization.rb', line 29

def qstamp(quantum = nil, pattern: nil, time: nil)
  # Handle default values and array input
  quantum, pattern = quantum if quantum.is_a?(Array)

  # Previously we erronously included `@opts.fetch(:quantize, nil)` in
  # the list of default values here, but @opts is for horreum instances
  # not at the class level. This method `qstamp` is part of the initial
  # definition for whatever horreum subclass we're in right now. That's
  # why default_expiration works (e.g. `class Plop; feature :quantization; default_expiration 90; end`).
  quantum ||= default_expiration || 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