Thomas Watson
Thomas Watson

Reputation: 6627

Which is the best/most used singleton coding convention in Ruby?

In the Ruby Standard Library we have the Singleton class:
http://ruby-doc.org/stdlib/libdoc/singleton/rdoc/index.html

We can make any class a singleton by including this class inside. I just rarely see this used. When would it make sense to use this Singleton class vs. just using plain old class methods - also known as singleton methods?

Said in another way: Which Singleton coding-convention are the best and why? Here are three ways I could think of:

require 'singleton'
class Foo
  include Singleton
  # method definitions go here...
end

Foo.instance.do_something!

Versus

class Foo
  class << self
    # method definitions go here...
  end
end

Foo.do_something!

Versus

module Foo
  class << self
    # method definitions go here...
  end
end

Foo.do_something!

Upvotes: 3

Views: 230

Answers (2)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

WARNING: Opinions ahead!


If you just need a single object, just use a single object:

class << (Foo = Object.new)
  # method definitions go here...
end

Foo.do_something!

Modules are for sharing behavior between objects. Classes are factories for objects. Note the plural: if you have only one object, you need neither a facility for sharing behavior nor a factory for producing multiple copies.

Whether or not this is considered idiomatic Ruby depends largely on which "Ruby" you are talking about: are you talking about Ruby as used by Rails programmers, Ruby as used by Smalltalk programmers, Ruby as used by Java programmers or Ruby as used by Ruby programmers? There are significant differences in the styles used by these different communities.

For example, old time Rubyists like David Alan Black tend to start always with just objects and singleton methods. Only if they later on discover duplicated behavior between objects will they extract that behavior into a mixin and extend the objects with it. (Note that at this stage, there still aren't any classes!)

Classes are created, again, only by refactoring, not by upfront design, when and only when there is duplicated structure between objects.

Upvotes: 4

Chuck
Chuck

Reputation: 237060

The most common approach I've seen is neither a singleton nor a class that you never instantiate. The most common and idiomatic way to do this is a module.

Upvotes: 0

Related Questions