Sha256: bf56306002abf83ebef07197d919a77cec86e593302f3ffde70c30650bf2e6d4

Contents?: true

Size: 1.32 KB

Versions: 2

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

module MrCommon
  # Helper class for building time zone select options. Pares down the list by
  # grouping locations that share ones or offsets.
  class Timezone
    class << self
      # @return [Array<String>] list of time zone names ordered by offset
      def time_zone_options
        filtered_time_zones.collect(&:name)
      end

      # @return [Array<Array<String, String>>] list of label value pairs for
      #   building time zone select options ordered by offset.
      def time_zone_select_options
        filtered_time_zones.collect do |tz|
          ["(UTC#{tz_utc_offset(tz)}) #{tz_friendly_name(tz)}", tz.name]
        end
      end

      private
        def all_time_zones
          @timezones ||= TZInfo::Timezone.all.sort_by { |tz| tz.current_period.utc_total_offset }
        end

        # Include only timezones that have a translation available
        def filtered_time_zones
          @filtered_timezones ||= all_time_zones.collect do |tz|
            next unless tz_friendly_name(tz)
            tz
          end.compact
        end

        def tz_friendly_name(tz)
          I18n.t(tz.name, scope: :timezones, default: false)
        end

        def tz_utc_offset(tz)
          ActiveSupport::TimeZone.seconds_to_utc_offset(tz.current_period.utc_total_offset)
        end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mr_common-2.1.0 app/models/mr_common/timezone.rb
mr_common-2.0.0 app/models/mr_common/timezone.rb