In ruby, as class are singleton objects, does anyone have any ideas when
a a singleton object should be used vs. simply adding methods to the
class?
I always include Singleton, but I see what you mean. A better way might be to
do it with modules:
module Foo
def self.bar
end
end
One example is mixins, though. For example, here:
class Foo
def self.bar
end
end
A mixin would almost certainly be expecting to be mixed via "include" here,
not "extend". This might not always matter, but some mixins will define
things like self.included, and won't work at all if you try to extend them
instead.
However, a mixin which expected "extend" would still work on a Singleton
object:
class Foo
include Singleton
def bar
end
end
Foo.instance.extend SomeMixin
I think the main reason for doing Singleton, though, is that it expresses
intent better, and it prevents the class from being instantiated -- sure,
there are ways around it, but you're not going to accidentally call Foo.new
without getting an error.