Module: TimeCalc::Types

Extended by:
Types
Included in:
Types
Defined in:
lib/time_calc/types.rb

Overview

Tries to encapsulate all the differences between Time, Date, DateTime

Constant Summary collapse

ATTRS =
{
  Time => i[year month day hour min sec subsec utc_offset],
  Date => i[year month day],
  DateTime => i[year month day hour min sec sec_fraction zone]
}.freeze

Instance Method Summary collapse

Instance Method Details

#compare(v1, v2) ⇒ Object



19
20
21
# File 'lib/time_calc/types.rb', line 19

def compare(v1, v2)
  compatible?(v1, v2) ? v1 <=> v2 : v1.to_time <=> v2.to_time
end

#compatible?(v1, v2) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/time_calc/types.rb', line 15

def compatible?(v1, v2)
  [v1, v2].all?(Date) || [v1, v2].all?(Time)
end

#convert(v, klass) ⇒ Object



23
24
25
26
27
# File 'lib/time_calc/types.rb', line 23

def convert(v, klass)
  return v if v.class == klass

  v.public_send("to_#{klass.name.downcase}")
end

#merge_date(value, **attrs) ⇒ Object



38
39
40
# File 'lib/time_calc/types.rb', line 38

def merge_date(value, **attrs)
  _merge(value, **attrs).values.then { |components| Date.new(*components) }
end

#merge_datetime(value, **attrs) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/time_calc/types.rb', line 42

def merge_datetime(value, **attrs)
  # When we truncate, we use :subsec key as a sign to zeroefy second fractions
  attrs[:sec_fraction] ||= attrs.delete(:subsec) if attrs.key?(:subsec)

  _merge(value, **attrs)
    .tap { |h| h[:sec] += h.delete(:sec_fraction) }
    .values.then { |components| DateTime.new(*components) }
end

#merge_time(value, **attrs) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/time_calc/types.rb', line 29

def merge_time(value, **attrs)
  _merge(value, **attrs)
    .tap { |h|
      h[:sec] += h.delete(:subsec)
      h[:utc_offset] = value.zone if value.zone.respond_to?(:utc_to_local) # Ruby 2.6 real timezones
    }
    .values.then { |components| Time.new(*components) }
end