To write a quicky document format with RubyLanguage, follow these simple steps:
Put primitive data types into a dictionary:
settings = { 'name' => aGadget.getName(), 'source' => aGadget.getSource(), 'xy' => aGadget.getXY() }Open a file, and "inspect" in the dictionary. This writes, as text, the Ruby source required to declare that dictionary, and all its primitive contents, as a constant literal dictionary declaration:
f.write(settings.inspect())To read, scoop out the file contents and drop them into "eval". This reconstitutes the dictionary:
f = File.open (fileName) fileContents = f.read() f.close() settings = eval(fileContents)--PhlIp
This is documented as the Active File pattern at http://www.doc.ic.ac.uk/~np2/patterns/scripting/data-as-code.html. --NatPryce
What if some malicious person alters your file and puts in the Ruby equivalent of "rm -rf /"?
If you need to deal with potentially hostile data, then either use Ruby's security features, or just use some other format.
Is there some reason why your reconstitution code isn't just:
settings = eval(File.read(fileName))(If the File.read method doesn't exist in your version of Ruby, add it. ;)
'Cause we should BreakLongLines when there are too many activities on one line.
OK, but this is Ruby -- we don't have to be so verbose to say it clearly:
file_contents = File.open file_name {|f| f.read} settings = eval file_contentsor using read as described above:
file_contents = File.read file_name settings = eval file_contents
To pump entire objects thru this system, override 'inspect' and make it emit a call to the object's constructor with enough arguments to re-construct it sufficiently for reconstitution purposes.
Is there a reason that you use this method and not RubyLanguage's Marshal (http://www.rubycentral.com/book/ref_m_marshal.html#Marshal.dump) class?
Marshal is a much better alternative in most cases. This seems like re-inventing the wheel. For the love of DRY, people, use what Matz gave ya!