Class: JobManager::OpenOnFirstWriteFile
- Inherits:
-
Object
- Object
- JobManager::OpenOnFirstWriteFile
- Defined in:
- lib/jobmanager/openonfirstwritefile.rb
Overview
This class represents a stream that wraps a file stream. Its only purpose is to defer the opening of the file to first write. Thus, if the file is never written to, it is never created!
Instance Method Summary collapse
- #close ⇒ Object
- #flush ⇒ Object
-
#initialize(file_name, mode_string) ⇒ OpenOnFirstWriteFile
constructor
A new instance of OpenOnFirstWriteFile.
-
#method_missing(*args, &block) ⇒ Object
Description: This method first opens the file (if not already opened), and then forwards the call to the file stream.
Constructor Details
#initialize(file_name, mode_string) ⇒ OpenOnFirstWriteFile
Returns a new instance of OpenOnFirstWriteFile.
11 12 13 14 15 |
# File 'lib/jobmanager/openonfirstwritefile.rb', line 11 def initialize(file_name, mode_string) @file_name = file_name @mode_string = mode_string @stream = nil end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(*args, &block) ⇒ Object
Description:
This method first opens the file (if not already opened), and then forwards the call to the file stream.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/jobmanager/openonfirstwritefile.rb', line 42 def method_missing(*args, &block) method = args.shift if (!@stream) directory = File.dirname(@file_name) begin FileUtils.mkdir_p(directory) rescue => e raise "Failed to create directory #{directory}, Error (#{e.class}): #{e.}" end begin @stream = File.new(@file_name, @mode_string) rescue => e raise "Failed to open file #{@file_name}, Error (#{e.class}): #{e.}" end end @stream.send(method, *args) end |
Instance Method Details
#close ⇒ Object
17 18 19 20 21 22 23 24 25 |
# File 'lib/jobmanager/openonfirstwritefile.rb', line 17 def close() # This method needs to be explicitly defined. If it wasn't, # method_missing would create the file in order to close it, # defeating the purpose of this class. if (@stream) @stream.close() end end |
#flush ⇒ Object
27 28 29 30 31 32 33 34 35 |
# File 'lib/jobmanager/openonfirstwritefile.rb', line 27 def flush() # This method needs to be explicitly defined. If it wasn't, # method_missing would create the file in order to flush it, # defeating the purpose of this class. if (@stream) @stream.flush() end end |