Sha256: 915bd33c9cd4030c353d0bfe6297b2c5f9eb4db85045f930a4b654fe49aca32b

Contents?: true

Size: 1.22 KB

Versions: 2

Compression:

Stored size: 1.22 KB

Contents

module StatusPageVi
  module Recordable
    def self.included(klass)
      klass.extend(RecordableClassMethods)
    end

    module RecordableClassMethods
      def save(service)
        data = collection.merge(service)
        update_storage(data)

        @collection = nil
      end

      def list
        collection.map do |timestamp, options|
          self.new(timestamp, options)
        end
      end

      def cache_file_path
        "#{__dir__}/../../../cache/#{self}.json"
      end

      def update_storage(data)
        File.delete(cache_file_path) if File.exist?(cache_file_path)
        write_to_service_file(data)
      end

      private

      def collection
        @collection ||= begin
          JSON.parse(File.read(cache_file_path))
        rescue Errno::ENOENT
          {}
        end
      end

      def write_to_service_file(data)
        Dir.mkdir("#{__dir__}/../../../cache") unless Dir.exists?("#{__dir__}/../../../cache")
        File.open(cache_file_path, "w") { |file| file.write(data.to_json) }
      end
    end

    def initialize(timestamp = nil, options = {})
      self.timestamp = timestamp
      self.options = options
    end

    def save
      self.class.save(self.to_h)
      self
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
status_page_vi-0.3.1 lib/status_page_vi/modules/recordable.rb
status_page_vi-0.3.0 lib/status_page_vi/modules/recordable.rb