Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

15. Marshal > Saving Singletons

Saving Singletons

Let’s take a look at a concrete example of a problem mentioned earlier, namely, the inability to use marshaling to save and load a singleton. In singleton_m.rb I have created an instance of Object, ob, and then extended it in the form of a singleton class that is given the additional method, xxx:

singleton_m.rb

ob = Object.new

class << ob
    def xxx( aStr )
        @x = aStr
    end
end

The problem arises when I try to save this data to disk using Marshal.dump. Ruby displays an error message: “singleton can’t be dumped (TypeError).”

YAML and Singletons

Before considering how you might deal with this, let’s briefly take a look at how YAML would cope in this situation. The program singleton_y.rb tries to save the singleton that I created a moment ago using YAML.dump, and, unlike Marshal.dump, it succeeds—well, sort of:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint