Sha256: d5cdf78efaa0fb837b136e962c00d37291117936f8da3a9f0eed429eae7c86ae

Contents?: true

Size: 1.4 KB

Versions: 9

Compression:

Stored size: 1.4 KB

Contents

# frozen_string_literal: true

require 'timezone/error'

module Timezone # rubocop:disable Style/Documentation
  # Responsible for loading and parsing timezone data from files.
  module Loader
    ZONE_FILE_PATH = File.expand_path(File.dirname(__FILE__) + '/../../data')
    SOURCE_BIT = 0

    class << self
      def load(name)
        raise ::Timezone::Error::InvalidZone unless valid?(name)

        @rules ||= {}
        @rules[name] ||= parse_zone_data(get_zone_data(name))
      end

      def names
        @names ||= parse_zone_names
      end

      def valid?(name)
        names.include?(name)
      end

      private

      def parse_zone_names
        files = Dir[File.join(ZONE_FILE_PATH, '**/*')].map do |file|
          next if File.directory?(file)

          file.sub("#{ZONE_FILE_PATH}/", '')
        end

        files.compact
      end

      def parse_zone_data(data)
        rules = []

        data.split("\n").each do |line|
          source, name, dst, offset = line.split(':')
          source = source.to_i
          dst = dst == '1'
          offset = offset.to_i
          source = rules.last[SOURCE_BIT] + source if rules.last
          rules << [source, name, dst, offset]
        end

        rules
      end

      # Retrieve the data from a particular time zone
      def get_zone_data(name)
        File.read(File.join(ZONE_FILE_PATH, name))
      end
    end
  end

  private_constant :Loader
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
timezone-1.3.4 lib/timezone/loader.rb
timezone-1.3.3 lib/timezone/loader.rb
timezone-1.3.2 lib/timezone/loader.rb
timezone-1.3.1 lib/timezone/loader.rb
timezone-1.3.0 lib/timezone/loader.rb
timezone-1.2.12 lib/timezone/loader.rb
timezone-1.2.11 lib/timezone/loader.rb
timezone-1.2.10 lib/timezone/loader.rb
timezone-1.2.9 lib/timezone/loader.rb