Module: Montrose::Utils

Included in:
Day, Month, Options
Defined in:
lib/montrose/utils.rb

Constant Summary collapse

MAX_HOURS_IN_DAY =
24
MAX_DAYS_IN_YEAR =
366
MAX_WEEKS_IN_YEAR =
53
MAX_DAYS_IN_MONTH =
31

Class Method Summary collapse

Class Method Details

.as_date(time) ⇒ Object



31
32
33
# File 'lib/montrose/utils.rb', line 31

def as_date(time)
  as_time(time).to_date
end

.as_time(time) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/montrose/utils.rb', line 12

def as_time(time)
  return nil unless time

  if time.is_a?(String)
    parse_time(time)
  elsif time.is_a?(ActiveSupport::TimeWithZone)
    time
  elsif time.respond_to?(:to_time)
    time.to_time
  else
    Array(time).flat_map { |d| as_time(d) }
  end
end

.current_timeObject



39
40
41
# File 'lib/montrose/utils.rb', line 39

def current_time
  ::Time.current
end

.days_in_month(month, year = current_time.year) ⇒ Object



43
44
45
46
# File 'lib/montrose/utils.rb', line 43

def days_in_month(month, year = current_time.year)
  date = ::Date.new(year, month, 1)
  ((date >> 1) - date).to_i
end

.days_in_year(year) ⇒ Object

Returns the number of days in the given year. If no year is specified, it will use the current year. github.com/rails/rails/pull/22244



51
52
53
# File 'lib/montrose/utils.rb', line 51

def days_in_year(year)
  ::Montrose::Utils.days_in_month(2, year) + 337
end

.normalize_time(time) ⇒ Object

Recurrence at fractions of a second are not recognized



27
28
29
# File 'lib/montrose/utils.rb', line 27

def normalize_time(time)
  time&.change(usec: 0)
end

.parse_time(*args) ⇒ Object



35
36
37
# File 'lib/montrose/utils.rb', line 35

def parse_time(*args)
  ::Time.zone.nil? ? ::Time.parse(*args) : ::Time.zone.parse(*args)
end

.to_index(string) ⇒ Object

Returns string.to_i only if string fully matches an integer otherwise ensures that return value won’t match a valid index



57
58
59
# File 'lib/montrose/utils.rb', line 57

def to_index(string)
  /^\d+/.match?(string) ? string.to_i : -1
end