Sha256: 51afb0f58f2e405bcab6d1046a7e2eb831466ca85d639ad971370c959c6f2868

Contents?: true

Size: 1.26 KB

Versions: 5

Compression:

Stored size: 1.26 KB

Contents

require 'timezone/error'

module Timezone
  module Loader
    ZONE_FILE_PATH = File.expand_path(File.dirname(__FILE__)+'/../../data')
    SOURCE_BIT = 0

    class << self
      def load(zone)
        @rules ||= {}
        @rules[zone] ||= parse_zone_data(get_zone_data(zone))
      end

      def names
        @@names ||= parse_zone_names
      end

      private

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

          file.gsub("#{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(zone)
        file = File.join(ZONE_FILE_PATH, zone)

        if !File.exists?(file)
          raise Timezone::Error::InvalidZone, "'#{zone}' is not a valid zone."
        end

        File.read(file)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
timezone-0.6.0 lib/timezone/loader.rb
timezone-0.5.0 lib/timezone/loader.rb
timezone-0.4.3 lib/timezone/loader.rb
timezone-0.4.2 lib/timezone/loader.rb
timezone-0.4.1 lib/timezone/loader.rb