Module: TimeZoneAble

Extended by:
ActiveSupport::Concern
Defined in:
lib/app/models/concerns/time_zone_able.rb

Overview

Objects that can localize time to it, kicking out safe uses of a date format.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/app/models/concerns/time_zone_able.rb', line 9

def self.included(base)
  base.class_eval do
    #
    # Fields
    #
    field :time_zone, type: String
    #
    # Validations
    #
    validates :time_zone, inclusion: TZInfo::Timezone.all_identifiers, presence: true
    #
    # Callbacks
    #
    before_validation :default_time_zone
  end
end

Instance Method Details

#default_time_zoneObject



67
68
69
# File 'lib/app/models/concerns/time_zone_able.rb', line 67

def default_time_zone
  self.time_zone ||= SystemConfiguration.default_time_zone
end

#local_date(date, format = :medium, default = 'N/A') ⇒ Object

Return the given time in the localized time for this object



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/app/models/concerns/time_zone_able.rb', line 33

def local_date(date, format = :medium, default = 'N/A')
  case date
  when Time
    tz = TZInfo::Timezone.get(time_zone.presence || SystemConfiguration.default_time_zone)
    date.present? ? I18n.l(date.in_time_zone(tz).to_date, format: format) : default
  when Date
    I18n.l(date, format: format)
  else
    default
  end
rescue StandardError
  default
end

#local_time(time, format = :medium, default = 'N/A') ⇒ Object

Return the given time in the localized time for this object



50
51
52
53
54
55
# File 'lib/app/models/concerns/time_zone_able.rb', line 50

def local_time(time, format = :medium, default = 'N/A')
  tz = TZInfo::Timezone.get(time_zone.presence || SystemConfiguration.default_time_zone)
  time.present? ? I18n.l(time.in_time_zone(tz), format: format) : default
rescue StandardError
  default
end

#local_updated_time(obj, format = :medium, default = 'N/A') ⇒ Object

Return the updated_at if found, otherwise return the created_at. If neither are there then return unknown



61
62
63
64
65
# File 'lib/app/models/concerns/time_zone_able.rb', line 61

def local_updated_time(obj, format = :medium, default = 'N/A')
  obj.updated_at.present? ? local_time(obj.updated_at, format, default) : local_time(created_at, format, default)
rescue StandardError
  default
end

#time_zone_optionsObject



26
27
28
# File 'lib/app/models/concerns/time_zone_able.rb', line 26

def time_zone_options
  TZInfo::Timezone.all_identifiers
end