Sha256: c6419782c76d9e50ec847205ca487d22740229fc1d2529c10470bf0feaa5925d

Contents?: true

Size: 1.46 KB

Versions: 21

Compression:

Stored size: 1.46 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

    @rules = {} # cache of loaded rules

    class << self
      def load(name)
        @rules.fetch(name) do
          raise ::Timezone::Error::InvalidZone unless valid?(name)

          @rules[name] = parse_zone_data(get_zone_data(name))
        end
      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

21 entries across 21 versions & 1 rubygems

Version Path
timezone-1.3.25 lib/timezone/loader.rb
timezone-1.3.24 lib/timezone/loader.rb
timezone-1.3.23 lib/timezone/loader.rb
timezone-1.3.22 lib/timezone/loader.rb
timezone-1.3.21 lib/timezone/loader.rb
timezone-1.3.20 lib/timezone/loader.rb
timezone-1.3.19 lib/timezone/loader.rb
timezone-1.3.18 lib/timezone/loader.rb
timezone-1.3.17 lib/timezone/loader.rb
timezone-1.3.16 lib/timezone/loader.rb
timezone-1.3.15 lib/timezone/loader.rb
timezone-1.3.14 lib/timezone/loader.rb
timezone-1.3.13 lib/timezone/loader.rb
timezone-1.3.12 lib/timezone/loader.rb
timezone-1.3.11 lib/timezone/loader.rb
timezone-1.3.10 lib/timezone/loader.rb
timezone-1.3.9 lib/timezone/loader.rb
timezone-1.3.8 lib/timezone/loader.rb
timezone-1.3.7 lib/timezone/loader.rb
timezone-1.3.6 lib/timezone/loader.rb