Module: Ghaki::CoreExt::File::WithTemp
- Defined in:
- lib/ghaki/core_ext/file/with_temp.rb
Overview
Helpers dealing with auto-cleaning up temp files.
Instance Method Summary collapse
-
#dump_via_temp(data_str, final_name, mode = 'w', *args) ⇒ Object
Simple helper for dumping a string to an output file using a temp.
-
#make_temp_name(final_name) ⇒ Object
Generate temp filename from given filename.
-
#with_named_temp(final_name) ⇒ Object
Calls block with temp filename then overwrites target filename if no exceptions occur.
-
#with_opened_temp(final_name, mode = 'w', *args) ⇒ Object
Opens writable temp file, renames to proper name if no exceptions.
Instance Method Details
#dump_via_temp(data_str, final_name, mode = 'w', *args) ⇒ Object
Simple helper for dumping a string to an output file using a temp.
34 35 36 37 38 |
# File 'lib/ghaki/core_ext/file/with_temp.rb', line 34 def dump_via_temp data_str, final_name, mode='w', *args with_opened_temp final_name, mode, *args do |tmp_file| tmp_file.puts data_str end end |
#make_temp_name(final_name) ⇒ Object
Generate temp filename from given filename.
9 10 11 12 13 |
# File 'lib/ghaki/core_ext/file/with_temp.rb', line 9 def make_temp_name final_name ::File.dirname(final_name) + ::File::Separator + '_tmp_' + $$.to_s + '.' + ::File.basename(final_name) end |
#with_named_temp(final_name) ⇒ Object
Calls block with temp filename then overwrites target filename if no exceptions occur.
16 17 18 19 20 21 22 |
# File 'lib/ghaki/core_ext/file/with_temp.rb', line 16 def with_named_temp final_name tmp_name = make_temp_name(final_name) yield tmp_name ::File.rename tmp_name, final_name if ::File.exists?(tmp_name) ensure ::File.unlink tmp_name if ::File.exists?(tmp_name) end |
#with_opened_temp(final_name, mode = 'w', *args) ⇒ Object
Opens writable temp file, renames to proper name if no exceptions.
25 26 27 28 29 30 31 |
# File 'lib/ghaki/core_ext/file/with_temp.rb', line 25 def with_opened_temp final_name, mode='w', *args with_named_temp final_name do |tmp_name| ::File.open(tmp_name,mode,*args) do |tmp_file| yield tmp_file end end end |