Difference between revisions of "Text File Writer Assignment"
Jump to navigation
Jump to search
(→Client) |
(→Client) |
||
Line 26: | Line 26: | ||
file.write("<html><body><h1>#{Time.now}</h1></body></html>") | file.write("<html><body><h1>#{Time.now}</h1></body></html>") | ||
end</nowiki> | end</nowiki> | ||
+ | |||
+ | =Testing Your Solution= | ||
+ | {{RubyUnitTest|text_file_utils|text_file_utils}} |
Revision as of 05:16, 25 November 2022
Contents
Background
Ensure
Ruby provides begin/rescue/ensure which is rather analogous to try/catch/finally in Java.
note: although coincidental, it is rather fitting that this reference covers begin/rescue/ensure with ensuring to close an opened file as its example. Ensuring to close an opened file is the canonical example for this sort of feature.
Yield
Code To Implement
TextFileUtils
file: | src/main/ruby/text_file_utils/text_file_utils.rb | |
class: | TextFileUtils | |
superclass: | Object | |
methods: | write_text(path) |
write_text(path)
Create a new File for the specified path in write mode.
If a block is given, yield the file to that block and ensure that you close the file. Return the closed file.
If no block is given, return the opened file.
Client
file to run: | src/main/ruby/text_file_utils/text_file_utils.rb |
In the same file you edit class TextFileUtils, you will find a simple client:
TextFileUtils.write_text(path) do |file| file.write("<html><body><h1>#{Time.now}</h1></body></html>") end
Testing Your Solution
file: | src/test/ruby/text_file_utils/text_file_utils.rb | UnitTest |
note: ensure that you have removed all printing to receive credit for any assignment.