Saturday, June 2, 2007

Singletons in Ruby

So I was reading my great-big-book-of-everything-Ruby the other night and figured I'd better post this before I forget.
I've used singletons quite a bit in c#, but have never really used them in any dynamic languages (Python, Ruby) that I've used. I found two different approaches to this and will post them both with a few explanations...

The first (which looks somewhat familiar)

class SingletonClass
  private_class_method :new
  @@singletonClass = nil
    @@singletonClass = new unless @@singletonClass

The first line is just a simple class declaration
Line two (which is a little different if you're coming from another language, like me:) ) makes the 'new' call to this class private so you cannot directly create new instances. "private_class_method makes existing class methods private".
Then we have our method that returns the instance of our singleton class
Line five will set the variable '@@singletonClass' to a new instance of the class unless it has already been set.
Now lastly my most undesired feature in Ruby. The single line "@@singletonClass" returns the variable. In Ruby every method returns the last thing. Since our last line was our variable that is what is returned.

The second (quite a bit different than what I'm used to)

require 'singleton'
class SingletonClass2
  include Singleton

Whoa! that's it? That's all you need to do for the second approach.
The third line ('include Singleton') is taking advantage of a Ruby feature called mixins.

1 comment:

Katie! said...

Anyone ever watch the kids show "Stanley"? Your referral to the "great big book of everything Ruby" reminds me of Stanley's great big book of everything (enter singing cat and dog).