Sha256: a208081ad2890c25cedca98cf2b0b62b6a7517e3f27d091f985bc366cfaccdd3

Contents?: true

Size: 1.22 KB

Versions: 62

Compression:

Stored size: 1.22 KB

Contents

require 'tmpdir'

module Nanoc::Int
  # @api private
  class TempFilenameFactory
    # @return [String] The root directory for all temporary filenames
    attr_reader :root_dir

    # @return [Nanoc::Int::TempFilenameFactory] A common instance
    def self.instance
      @instance ||= new
    end

    def initialize
      @counts = {}
      @root_dir = Dir.mktmpdir('nanoc')
    end

    # @param [String] prefix A string prefix to include in the temporary
    #   filename, often the type of filename being provided.
    #
    # @return [String] A new unused filename
    def create(prefix)
      count = @counts.fetch(prefix, 0)
      @counts[prefix] = count + 1

      dirname  = File.join(@root_dir, prefix)
      filename = File.join(@root_dir, prefix, count.to_s)

      FileUtils.mkdir_p(dirname)

      filename
    end

    # @param [String] prefix A string prefix that indicates which temporary
    #   filenames should be deleted.
    #
    # @return [void]
    def cleanup(prefix)
      path = File.join(@root_dir, prefix)
      if File.exist?(path)
        FileUtils.rm_rf(path)
      end

      @counts.delete(prefix)

      if @counts.empty? && File.directory?(@root_dir)
        FileUtils.rm_rf(@root_dir)
      end
    end
  end
end

Version data entries

62 entries across 62 versions & 1 rubygems

Version Path
nanoc-4.7.9 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.7.8 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.7.7 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.7.6 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.7.5 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.7.4 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.7.3 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.7.2 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.7.1 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.7.0 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.6.4 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.6.3 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.6.2 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.6.1 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.6.0 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.5.4 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.5.3 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.5.2 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.5.1 lib/nanoc/base/services/temp_filename_factory.rb
nanoc-4.5.0 lib/nanoc/base/services/temp_filename_factory.rb