Sha256: 4cc72a8aec9221eb3fe04e7aa00cccd6cf442ad1cdba5045248afcbe2843a809

Contents?: true

Size: 1.25 KB

Versions: 2

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

#
# Objects that can localize time to it, kicking out safe uses of a date format.
#
module TimeZoneAble
  extend ActiveSupport::Concern

  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

  #
  # Return the given time in the localized time for this object
  #
  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

  #
  # Return the updated_at if found, otherwise return the created_at. If neither are there
  # then return unknown
  #
  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

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
web47core-0.1.0 lib/app/models/concerns/time_zone_able.rb
web47core-0.0.10 lib/app/models/concerns/time_zone_able.rb