Module: OsCtl::Lib::Utils::File
- Defined in:
- lib/libosctl/utils/file.rb
Instance Method Summary collapse
- #regenerate_file(path, mode) ⇒ Object
-
#replace_symlink(path, dst) ⇒ Object
Atomically replace or create symlink.
- #rmdir_if_empty(path) ⇒ Object
- #unlink_if_exists(path) ⇒ Object
Instance Method Details
#regenerate_file(path, mode) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/libosctl/utils/file.rb', line 5 def regenerate_file(path, mode) replacement = "#{path}.new-#{SecureRandom.hex(3)}" File.open(replacement, 'w', mode) do |new| if File.exist?(path) File.open(path, 'r') do |old| yield(new, old) end else yield(new, nil) end end File.rename(replacement, path) end |
#replace_symlink(path, dst) ⇒ Object
Atomically replace or create symlink
25 26 27 28 29 |
# File 'lib/libosctl/utils/file.rb', line 25 def replace_symlink(path, dst) replacement = "#{path}.new-#{SecureRandom.hex(3)}" File.symlink(dst, replacement) File.rename(replacement, path) end |
#rmdir_if_empty(path) ⇒ Object
38 39 40 41 42 43 |
# File 'lib/libosctl/utils/file.rb', line 38 def rmdir_if_empty(path) Dir.rmdir(path) true rescue Errno::ENOTEMPTY false end |
#unlink_if_exists(path) ⇒ Object
31 32 33 34 35 36 |
# File 'lib/libosctl/utils/file.rb', line 31 def unlink_if_exists(path) File.unlink(path) true rescue Errno::ENOENT false end |