Module: Puree::Util::Date

Defined in:
lib/puree/util/date.rb

Overview

Date transformations

Class Method Summary collapse

Class Method Details

.hash_to_time(data) ⇒ Time

Converts a date with variable components present (year, month, day) to Time format.

Parameters:

  • data (Hash)

Returns:

  • (Time)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/puree/util/date.rb', line 13

def self.hash_to_time(data)
  h = normalise data
  if !h['year'].empty? && !h['month'].empty? && !h['day'].empty?
    return Time.new h['year'].to_i,
                    h['month'].to_i,
                    h['day'].to_i
  end
  if !h['year'].empty? && !h['month'].empty?
    return Time.new h['year'].to_i,
                    h['month'].to_i
  end
  if !h['year'].empty?
    return Time.new h['year'].to_i
  end
  nil
end

.iso(data) ⇒ String

Converts a date with three components (year, month, day) to ISO 8601 date format.

Parameters:

  • data (Hash)

Returns:

  • (String)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/puree/util/date.rb', line 34

def self.iso(data)
  iso_date = ''
  year =  data['year']
  month = data['month']
  day = data['day']
  if !year.empty?
    iso_date << year
  else
    iso_date
  end
  if !month.empty?
    # Add leading zero to convert to ISO 8601 date component
    if month.length < 2
      month.insert(0, '0')
    end
    iso_date << '-' + month
  else
    iso_date
  end
  if !day.empty?
    # Add leading zero to convert to ISO 8601 date component
    if day.length < 2
      day.insert(0, '0')
    end
    iso_date << '-' + day
  end
  iso_date
end

.normalise(data) ⇒ Hash

Forces a date to have three components (year, month, day).

Parameters:

  • data (Hash)

Returns:

  • (Hash)


67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/puree/util/date.rb', line 67

def self.normalise(data)
  if !data.nil? && !data.empty?
    date = {}
    year =  data['year']
    month = data['month']
    day = data['day']
    date['year'] = year ? year : ''
    date['month'] = month ? month : ''
    date['day'] = day ? day : ''
    date
  else
    {}
  end
end