class MarshalFile
Marshal File Writing and Reading¶ ↑
Write Example:¶ ↑
a = {1=>2, 3=>4} c = {5=>6, 7=>8} mf = MarshalFile.new("test.marshal","write") mf.write(a) mf.write(c) mf.close
Read Example:¶ ↑
mf = MarshalFile.new("test.marshal") while !mf.eof puts mf.read end mf.close
Public Class Methods
new(filename = nil,mode="read")
click to toggle source
initialize parameters:¶ ↑
filename = name of file mode = "read" (default), "write", "append"
# File lib/marshal_file.rb, line 25 def initialize(filename = nil,mode="read") @filename = filename if @filename == nil @filename = File.join(Rails.root, 'log', 'NoName-'+Time.now.localtime.strftime("%Y-%m-%d")+".marshal") end @open = true if mode == "read" if FileTest::exist?(@filename) @file = File.open(@filename, 'rb') else @open = false puts @filename + " not found" end end if mode == "write" @file = File.open(@filename, 'wb') end if mode == "append" @file = File.open(@filename, 'ab') end end
Public Instance Methods
close()
click to toggle source
close the marshal file
# File lib/marshal_file.rb, line 86 def close if @open @file.close @open = false end end
delete()
click to toggle source
delete the marshal file.
# File lib/marshal_file.rb, line 95 def delete if @open close end if FileTest::exist?(@filename) File.delete(@filename) else puts @filename + " does not exist" end end
eof()
click to toggle source
check for eof while !mf.eof
puts mf.read
end
# File lib/marshal_file.rb, line 52 def eof if @open return @file.eof? else puts "file not open for reading" return false end end
read()
click to toggle source
read from marshal file must be opened in read mode
# File lib/marshal_file.rb, line 64 def read if @open return Marshal.load(@file) else puts "file not open for reading" end end
write(val)
click to toggle source
write to marshal file must be opened in append or write mode
# File lib/marshal_file.rb, line 75 def write(val) if @open Marshal.dump(val,@file) else puts "file not open for writing" end end