Class: TimeRange

Inherits:
Range
  • Object
show all
Defined in:
lib/time_range.rb,
lib/time_range/time.rb,
lib/time_range/version.rb,
lib/time_range/advancer.rb

Overview

Range over Time stepping by time intervals.

Does not require ActiveSupport.

Unlike a Range, it is necessary to call #by to say how long between each step.

Examples:

Print every week of 2024.

TimeRange
  .new(Time.local(2024), Time.local(2025), true)
  .by(weeks: 1)
  .each { |week| puts week }

Constant Summary collapse

VERSION =

TimeRange version

"0.1.0"

Instance Method Summary collapse

Constructor Details

#initialize(first, last, exclude_last = false) ⇒ TimeRange

Same as Range.new, but it takes Time objects.

Parameters:

  • first (Time)

    the beginning of the range

  • last (Time)

    the end of the range

  • exclude_last (Boolean) (defaults to: false)

    if true, exclude the last value from the range, default false

See Also:

  • Range.new


26
27
28
29
30
31
32
# File 'lib/time_range.rb', line 26

def initialize(first, last, exclude_last = false) # rubocop:disable Style/OptionalBooleanParameter
  super(
    first ? TimeRange::Time.new(first) : first,
    last ? TimeRange::Time.new(last) : last,
    exclude_last
  )
end

Instance Method Details

#by(seconds: nil, minutes: nil, hours: nil, days: nil, weeks: nil, months: nil, years: nil) ⇒ TimeRange

The time interval to use when iterating through the TimeRange.

Returns the TimeRange object so you can safely chain time_range = TimeRange.new(…).by(…)

Currently cannot be negative.

Parameters:

  • seconds (Numeric) (defaults to: nil)
  • minutes (Numeric) (defaults to: nil)
  • hours (Numeric) (defaults to: nil)
  • days (Numeric) (defaults to: nil)
  • weeks (Numeric) (defaults to: nil)
  • months (Numeric) (defaults to: nil)
  • years (Numeric) (defaults to: nil)

Returns:



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/time_range.rb', line 50

def by( # rubocop:disable Metrics/ParameterLists
  seconds: nil, minutes: nil, hours: nil,
  days: nil, weeks: nil, months: nil, years: nil
)
  by = {
    seconds: seconds, minutes: minutes, hours: hours,
    days: days, weeks: weeks, months: months, years: years
  }.compact!

  self.begin&.by = by
  self.end&.by = by

  return self
end

#eql?(other) ⇒ Boolean

Like Range#eql?, but will be false if their #by is different.

Returns:

  • (Boolean)


66
67
68
69
70
# File 'lib/time_range.rb', line 66

def eql?(other)
  return false if self.begin&.by != other.begin&.by || self.end&.by != other.end&.by

  super
end