class LX::File::Class

Public Class Methods

new(clss) click to toggle source
# File lib/lx.rb, line 455
def initialize(clss)
end

Public Instance Methods

atomic_write(path_final, content) click to toggle source

Atomically writes content to the given path. Does so by creating a temp file, writing to it, then renaming the temp file to the final destination.

# File lib/lx.rb, line 460
def atomic_write(path_final, content)
        begin
                path_tmp = path_final + '.' + rand.to_s.sub(/\A.*\./mu, '')
                File.write path_tmp, content
                File.rename path_tmp, path_final
        ensure
                if File.exist?(path_tmp)
                        File.delete path_tmp
                end
        end
end
temp_path(opts = {}) { |path| ... } click to toggle source

Creates a temporary path. Does not create a file. If, after the `do` block, a file exists at that path, that file is deleted.

# File lib/lx.rb, line 474
def temp_path(opts = {})
        opts = {'delete'=>true}.merge(opts)
        
        # root
        if opts['root']
                root = opts['root'].sub(/\/*\z/mu, '/')
        else
                root = './'
        end
        
        # full path
        path = root + LX.randstr
        
        # add extension
        if opts['ext']
                ext = opts['ext']
                ext = ext.sub(/\A\.*/mu, '.')
                path += ext
        end
        
        if block_given?
                begin
                        yield path
                ensure
                        if opts['delete'] and File.exist?(path)
                                File.delete path
                        end
                end
        else
                return path
        end
end