From: James Edward Gray II Date: 2006-08-02T22:57:49+09:00 Subject: Re: Can you explain what this repo (yaml/Marshal) code do? On Aug 2, 2006, at 5:35 AM, anne001 wrote: >> It looks like in this code, this is simply how the save and load >> functions are implemented, and since 'self' is being passed, it will >> just serialize the Repository object to file during save and restore >> it during load. > > but why do you need to save and load the objects, > I have never seen code like this before. What do you gain? > what is the problem that it resolves Well, let's pretend you had some wiki class in your code: # a mock wiki object... class WikiPage def initialize( page_name, author, contents ) @page_name = page_name @revisions = Array.new add_revision(author, contents) end attr_reader :page_name def add_revision( author, contents ) @revisions << { :created => Time.now, :author => author, :contents => contents } end def wiki_page_references [@page_name] + @revisions.last[:contents].scan(/\b(?:[A-Z]+ [a-z]+){2,}/) end # ... end Now, let's assume you have a Hash of these things you are using to run your wiki: wiki = Hash.new [ ["HomePage", "James", "A page about the SillyEmailExamples..."], ["SillyEmailExamples", "James", "Blah, blah, blah..."] ].each do |page| new_page = WikiPage.new(*page) wiki[new_page.page_name] = new_page end When your script runs you will need to save these pages to a disk somehow, so you don't lose the site contents between runs. You have a ton of options here, of course, including using a database or rolling some method that can write these pages out to files. Writing them out is a pain though because page contents can be pretty much anything, so you'll need to come up with a good file format that allows you to tell where each revision starts and stops. This probably means handling some escaping characters of some kind, at the minimum. Or, you can just use Marshal/YAML. With these helpers, saving the entire wiki is reduced to the trivial: File.open("wiki.dump", "w") { |file| Marshal.dump(wiki, file) } When needed, you can load that back with: wiki = File.open("wiki.dump") { |file| Marshal.load(file) } Those files will be stored in a binary format for Ruby to read. If you would prefer a human-readable format, replace the word Marshal with YAML above and make sure your script does a: require "yaml" See how easy it is to get instant saving/loading of entire Ruby structures? James Edward Gray II