Sha256: 5603c4ccbda621b97c0bc0c24e14340fe0c1128f4f16dd64c817b9c1c640f516

Contents?: true

Size: 1.46 KB

Versions: 52

Compression:

Stored size: 1.46 KB

Contents

# frozen_string_literal: true

require 'eac_ruby_utils/core_ext'
require 'eac_ruby_utils/yaml'
require 'fileutils'

module EacFs
  class StorageTree
    CONTENT_FILE_NAME = '__content__'

    attr_reader :path

    def initialize(*path_parts)
      raise ArgumentError, "\"#{path_parts}\" is empty" if path_parts.empty?

      @path = ::File.expand_path(::File.join(*path_parts.map(&:to_s)))
    end

    def clear
      return unless stored?

      ::File.unlink(content_path)
    end

    def read
      return nil unless stored?

      ::File.read(content_path)
    end

    def read_or_store
      write(yield) unless stored?

      read
    end

    # @return [Object]
    def read_or_store_yaml(use_cache = true)
      write_yaml(yield) unless stored? && use_cache

      read_yaml
    end

    # @return [Object, nil]
    def read_yaml
      r = read
      r.nil? ? nil : ::EacRubyUtils::Yaml.load(r)
    end

    def write(value)
      assert_directory_on_path
      ::File.write(content_path, value)
      value
    end

    def write_yaml(object)
      write(::EacRubyUtils::Yaml.dump(object))
      object
    end

    def child(*child_path_parts)
      self.class.new(path, *child_path_parts)
    end

    def stored?
      ::File.exist?(content_path)
    end

    def content_path
      ::File.join(path, CONTENT_FILE_NAME)
    end

    private

    def assert_directory_on_path
      raise "#{path} is a file" if ::File.file?(path)

      ::FileUtils.mkdir_p(path)
    end
  end
end

Version data entries

52 entries across 52 versions & 2 rubygems

Version Path
eac_tools-0.76.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.75.2 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.75.1 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.75.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.74.1 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.74.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.73.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.72.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.70.1 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.70.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.69.1 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.69.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.68.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.67.1 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.67.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.66.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.65.1 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.65.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.64.0 sub/eac_fs/lib/eac_fs/storage_tree.rb
eac_tools-0.63.0 sub/eac_fs/lib/eac_fs/storage_tree.rb