Module: Montrose::Utils

Included in:
Options
Defined in:
lib/montrose/utils.rb

Constant Summary collapse

MONTHS =
::Date::MONTHNAMES
DAYS =
::Date::DAYNAMES
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


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

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

.as_time(time) ⇒ Object


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

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


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

def current_time
  ::Time.current
end

.day_number(name) ⇒ Object


54
55
56
57
58
59
60
61
62
63
# File 'lib/montrose/utils.rb', line 54

def day_number(name)
  case name
  when 0..6
    name
  when Symbol, String
    DAYS.index(name.to_s.titleize)
  when Array
    day_number name.first
  end
end

.day_number!(name) ⇒ Object


65
66
67
68
# File 'lib/montrose/utils.rb', line 65

def day_number!(name)
  day_number(name) or fail ConfigurationError,
    "Did not recognize day #{name}, must be one of #{DAYS.inspect}"
end

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


70
71
72
73
# File 'lib/montrose/utils.rb', line 70

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


78
79
80
# File 'lib/montrose/utils.rb', line 78

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

.month_number(name) ⇒ Object


40
41
42
43
44
45
46
47
# File 'lib/montrose/utils.rb', line 40

def month_number(name)
  case name
  when Symbol, String
    MONTHS.index(name.to_s.titleize)
  when 1..12
    name
  end
end

.month_number!(name) ⇒ Object


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

def month_number!(name)
  month_number(name) or fail ConfigurationError,
    "Did not recognize month #{name}, must be one of #{MONTHS.inspect}"
end

.parse_time(*args) ⇒ Object


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

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