Created
December 1, 2014 12:00
-
-
Save rklemme/ff43ff3da7d786e28b29 to your computer and use it in GitHub Desktop.
How to marshal an object with open stream, file descriptor or other non serializable data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
class Logger | |
ENDL = "\n".freeze | |
def initialize(file_name) | |
@file_name = file_name | |
end | |
def log(message) | |
get_stream << message << ENDL | |
end | |
def close | |
# close and catch any error, e.g. from @stream being nil | |
@stream.close rescue nil | |
@stream = nil | |
end | |
def marshal_dump | |
@stream.flush rescue nil | |
@file_name | |
end | |
def marshal_load(data) | |
@file_name = data | |
end | |
private | |
def get_stream | |
@stream ||= File.open(@file_name, 'a') | |
end | |
end | |
File.delete "log.txt" | |
log = Logger.new "log.txt" | |
log.log "first" | |
log.log "second" | |
File.open("log.marshal", 'wb') {|io| Marshal.dump(log, io)} | |
log.log "third" | |
log.close # close this as we are overwriting variable log | |
log = File.open("log.marshal", 'rb') {|io| Marshal.load(io)} | |
log.log "fourth" | |
log.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment