Which is the best/most used singleton coding convention in Ruby? - 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!

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.

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.

Related

Using `extend self` and `class << self` in Ruby Modules

I sometimes write modules that will only contain module methods (as opposed to module instance methods) (are there better names for these?). These modules should not be included in classes because that would have no effect and be misleading to a reader. So I'd like it to be as clear as possible to the reader that these modules contain no instance methods.
If I define all methods with .self, then a reader has to inspect all methods to ensure that this module contains no instance methods. If I instead use class << self or extend self then it is automatic; as soon as the reader sees this, they know.
I think extend self is best becuase with class << self one has to find its corresponding end; that is, it may not apply to all methods in the module.
So is it a good idea, and a best practice, to use extend self in cases like this?
Also, is there any difference at runtime between enclosing all methods in class << self as opposed to using extend self?
I sometimes write modules that will only contain module methods (as opposed to module instance methods) (are there better names for these?).
Singleton, meaning a class with a single instance. Here that "single instance" is the Module instance.
If I define all methods with .self, then a reader has to inspect all methods to ensure that this module contains no instance methods
The module's documentation should make this clear. If the user of a module has to study the code to understand your module, that is a documentation failure.
What does extend self do?
So I'd like it to be as clear as possible to the reader that these modules contain no instance methods.
extend self does the opposite. It makes all the instance methods also be class methods. It's equivalent to YourModule.extend(YourModule).
module YourModule
def some_method
23
end
extend self
end
Is the same as...
module YourModule
def some_method
23
end
end
YourModule.extend(YourModule)
Which is similar to...
module YourModule
def some_method
23
end
def self.some_method
23
end
end
Why would you do this? To allow both...
YourModule.some_method
and also...
class SomeClass
extend YourModule
end
SomeClass.some_method
There are edge cases where you might want this, but for general use I would argue this is an anti-pattern. The first is using a module as a singleton, the second is using the module as a mixin or trait. These are two rather different design goals for a module. Trying to be both will compromise the design of both.
Pros and Cons.
Since the primary use case of being both a singleton and a mixin is an anti-pattern, I would argue use class << self, with def self.method occasionally, and module_function and extend self never.
class << self
Pros
All class definitions are grouped together.
The block scope makes it clear what affects the class and what affects the instances.
Indentation makes it clear what is in the block.
IDEs can clearly identify what is in the block.
It allows using normal declarations like attr_accessor on the class.
It is documented.
It is common.
Rubocop approved.
Cons
When looking at an individual method, it's not as obvious as def self.method.
def self.method
Pros
It's obvious it's a class method from looking at the method.
It is documented.
It is common.
Rubocop approved.
Cons
You might forget to add the self..
It allows mixing of class and instance methods making the reader hunt through the code.
It does not help using attr_accessor and friends on the class.
extend self
Pros
It allows your module to act as both a singleton (YourModule.method) and a mixin (extend YourModule)... which is also a con.
Cons
It is obscure; many (most?) won't know to look for it or what it means if they find it.
It is not documented (or if it is, I can't find it).
Individual methods look like instance methods.
It can appear anywhere in the module, and there's no consensus where it should go, making it action at a distance.
It affects the meaning of code before it, the one case I can think of this in Ruby, further making it action at a distance.
Rubocop prefers module_function to extend self, though doesn't explain why. For my guesses, see below.
It allows your module to act as both a singleton (YourModule.method) and a mixin (extend YourModule). Those are two rather different use cases making this an anti-pattern.
module_function
I've never heard of this either, but it came up when searching for extend self. I would also say to never use this, use class << self, but it's better than extend self.
Pros
It's at least mentioned in the Modules and Classes documentation.
It's documented.
It works like private in that it affects all methods below it (though this is also a con, see below).
If there are to be no instance methods, it must appear at the top of the module.
Rubocop approved.
Cons
It is obscure; many (most?) won't know to look for it or what it means when they find it.
Individual methods look like instance methods.
It affects the meaning of distant code after it making it action at a distance.
I don't see why it should matter how you decide to define the module methods. Consider simply raising an exception if the module is included in another module (which may be a class). You can do that with the callback (a.k.a. "hook") method Module#included. Here's an example.
module M
# This module is not to be included in a class because
# it contains no instance methods.
def self.included(klass)
raise "\nYou intended to include this module in #{klass}. You must be out of\nyour mind! It does no harm but there is no point in doing so\nbecause this module contains no instance methods. Duh!"
end
def self.hi
puts "Hi, guys"
end
end
M.hi
Hi, guys
class C
include M
end
RuntimeError:
You intended to include this module in C. You must be out of
your mind! It does no harm but there is no point in doing so
because this module contains no instance methods. Duh!

In Ruby, are the terms "metaclass", "eigenclass", and "singleton class" completely synonymous and fungible?

The docs for the Class class have an incredibly confusing diagram involving "metaclasses". I'm trying to demystify what's actually going on here. Are all three terms...
metaclass
eigenclass
singleton class
Synonymous in Ruby? I know that metaclass means something specific and different in Python, for example, but what about in Ruby?
tl;dr: Yes.
In the past, nobody knew what to call them, so everybody called them something else. Here is just a small sample of the names different authors have used or proposed over time:
singleton class
eigenclass
metaclass
ghost class
own class
virtual class
shadow class
myclass
selfclass
overclass
underclass
anchorclass
embedded class
intrinsic class
innate class
nameless class
unit class
atom class
singular class
singularity
bongo class
inner class
Originally, matz didn't want to choose a name, rather he wanted the community to settle on one. Unfortunately, it didn't. When matz and David Flanagan wrote The Ruby Programming Language, they had to choose, and they chose eigenclass (but singleton method). Eigenclass was also used in the first drafts for the ISO Ruby Language Specification (but mainly because it was very easy to run a search&replace on that name once an "official" one had been found).
However, in the later drafts and the final version of the ISO Ruby Language Specification, singleton class is used. That name was also chosen, when the Object#singleton_class accessor method was finally formally introduced in Ruby 1.9.2 and Module#singleton_class? was introduced in Ruby 2.1.
Metaclass was the term used by _why the lucky stiff in Why's (Poignant) Guide to Ruby (and other writings and libraries), which was highly influential on a whole generation of non-Japanese-speaking Ruby developers, and for a long time the best introduction to Ruby metaprogramming (and the only English one).
Nowadays, the terms singleton class and eigenclass seem to predominantly used (with singleton class taking over, thanks to the method names in the core library), with the occasional mention of metaclass.
Personally, I never liked metaclass, because it actually already has a different meaning: the metaclass is the class of a class. In Ruby, classes have two classes that define their behavior: their singleton class and the Class class, either one of which could be considered their metaclass. (Although neither of those classes can do what metaclasses in other languages can do, e.g. change the rules the method lookup or inheritance.)
Virtual class is even more problematic, because not only does it have a different meaning in programming in general (a nested class that can be overridden in a subclass, as in e.g. Beta or Newspeak, and proposed but abandoned for Scala), it even already has a third different meaning within the Ruby community: virtual class is the name given inside the MRI and YARV source code to singleton classes and include classes.
Inner class also already has a meaning as synonym to nested class (a class which is a member of an outer class, just like a method).
Personally, I always liked eigenclass, in symmetry to already established technical terms such as eigenvalue, eigenvector, eigenspace, eigenfunction, eigenface, eigenwave, eigenplane, eigenstate, eigenproblem etc. However, I have now adopted the term singleton class, simply because it's easier to talk about the singleton_class method as returning the singleton class.
Yes, the docs appear to be using metaclass to mean singleton class. Every class in the diagram inherits from a metaclass, whose name is the same as the class with some extra notation, which is also the format used for singleton classes, so they must mean singleton class.
Yes, they are all synonyms. Singleton class is the most often used term, and it makes some sense: every singleton class has only one instance.
As far as inheritance diagrams go, I've posted some that may be less confusing:
Ruby method lookup path for an object
They all mean the same, but I think the official terms are eigenclass and singleton class. It seems like metaclass (or meta-class) sneaked in due to the document (actually comments on the source) being edited by multiple people without consensus on the terms. It looks like eigenclass was used more in the earlier days, but as English-imperialist community (many of whom do not understand the morpheme "eigen") came to take over Ruby, singleton class became popular. And Matz does not seem to want to mix non-English words into method names, so ever since the method singleton_class has been introduced, it seems like singleton class became even more dominant.

Ruby YARD: documenting abstract methods implementations

I have a typical OO pattern: one base abstract class (that defines abstract methods) and several classes that implement these abstract methods in class-specific way.
I'm used to write documentation only once in abstract methods and then it automatically propagates to several concrete classes (at least it works the following way in Javadoc, in Scaladoc, in Doxygen), i.e. I don't need to repeat the same description in all concrete classes.
However, I couldn't find how to do such propagation in YARD. I've tried, for example:
# Some description of abstract class.
# #abstract
class AbstractClass
# Some method description.
# #return [Symbol] some return description
# #abstract
def do_something
raise AbstractMethodException.new
end
end
class ConcreteClass < AbstractClass
def do_something
puts "Real implementation here"
return :foo
end
end
What I get:
Code works as expected - i.e. throws AbstractMethodException is called in abstract class, does the job in concrete class
In YARD, AbstractClass is clearly defined as abstract, ConcreteClass is normal
Method description and return type is good in AbstractClass
Method is said to throw AbstractMethodException in AbstractClass
Method has no description at all and generic Object return type in ConcreteClass, there's not a single notice of that an abstract method exists in base class.
What I expect to get:
Method's description and return type are inherited (i.e. copied) to ConcreteClass from info at AbstractClass
Ideally, this method is specified in "inherited" or "implemented" section of ConcreteClass description, with some reference link from ConcreteClass#do_something to AbstractMethod#do_something.
Is it possible to do so?
I think the issue boils down to what you're trying to do. It looks like you're trying to implement an Interface in Ruby, which makes sense if you're coming from Java or .NET, but isn't really how Ruby developers tend to work.
Here is some info about how the typical thought on Interfaces in Ruby: What is java interface equivalent in Ruby?
That said, I understand what you're trying to do. If you don't want your AbstractClass to be implemented directly, but you want to define methods that can be used in a class that behaves like the AbstractClass stipulates (as in Design by Contract), then you probably want to use a Module. Modules work very well for keeping your code DRY, but they don't quite solve your problem related to documenting overridden methods. So, at this point I think you can reconsider how you approach documentation, or at least approach it in a more Ruby-ish way.
Inheritance in Ruby is really (generally speaking from my own experience) only used for a few reasons:
Reusable code and attributes
Default behaviors
Specialization
There are obviously other edge cases, but honestly this is what inheritance tends to be used for in Ruby. That doesn't mean what you're doing won't work or violates some rule, it just isn't typical in Ruby (or most dynamically typed languages). This atypical behavior is probably why YARD (and other Ruby doc generators) doesn't do what you expect. That said, creating an abstract class that only defines the methods that must exist in a subclass really gains you very little from a code perspective. Methods not defined will result in a NoMethodError exception being thrown anyway, and you could programmatically check if an object will respond to a method call (or any message for that matter) from whatever calls the method, using #respond_to?(:some_method) (or other reflective tools for getting meta stuff). It all comes back Ruby's use of Duck Typing.
For pure documentation, why document a method that you don't actually use? You shouldn't really care about the class of the object being sent or received from calling a method, just what those objects respond to. So don't bother creating your AbstractClass in the first place if it adds no real value here. If it contains methods you actually will call directly without overriding, then create a Module, document them there, and run $ yardoc --embed-mixins to include methods (and their descriptions) defined in mixed-in Modules. Otherwise, document methods where you actually implement them, as each implementation should be different (otherwise why re-implement it).
Here is how I would something similar to what you're doing:
# An awesome Module chock-full of reusable code
module Stuff
# A powerful method for doing things with stuff, mostly turning stuff into a Symbol
def do_stuff(thing)
if thing.kind_of?(String)
return thing.to_sym
else
return thing.to_s.to_sym
end
end
end
# Some description of the class
class ConcreteClass
include Stuff
# real (and only implementation)
def do_something
puts "Real implementation here"
return :foo
end
end
an_instance = ConcreteClass.new
an_instance.do_somthing # => :foo
# > Real implementation here
an_instance.do_stuff("bar") # => :bar
Running YARD (with --embed-mixins) will include the methods mixed-in from the Stuff module (along with their descriptions) and you now know that any object including the Stuff module will have the method you expect.
You may also want to look at Ruby Contracts, as it may be closer to what you're looking for to absolutely force methods to accept and return only the types of objects you want, but I'm not sure how that will play with YARD.
Not ideal, but you can still use the (see ParentClass#method) construct (documented here). Not ideal because you have to type this manually for every overriding method.
That being said, I'm no Yard specialist but given its especially customizable architecture, I'd be surprised that there would be no easy way to implement what you need just by extending Yard, somewhere in the Templates department I guess.

Singleton vs. Monostate Pattern in Ruby

Suppose a class needs to load an external library which takes some time to load and thus should be loaded only once. Two natural solutions to this would be to use the singleton pattern or the monostate pattern. Is there any advantage to either of these solutions in this particular context in Ruby?
For example:
# Using a Singleton class
require 'singleton'
class Parser
include Singleton
def initialize
#parser = load_external_library
end
def parse(sentence)
#parser.parse(sentence)
end
end
# Then calling using...
Parser.instance.parse(sentence)
Versus:
# Using a Monostate class
class Parser
def self.parse(sentence)
##parser ||= load_external_library
##parser.parse(sentence)
end
end
# Then calling using...
Parser.parse(sentence)
Since the second syntax is much cleaner, are there any advantages to using the Singleton in Ruby?
The singleton pattern structurally enforces the fact that you can never have more than one instance of a class at a time, and it is obvious to the developers that they are dealing with a singleton.
The monostate enforces the behavior of a singleton without the structure of the monostate.
You might find situations where you still need instance data. Therefore a monostate would be better. You can create the instance, use methods to affect instance data and still have access to the static data. With a singleton, you cannot have instance data.
Besides, If you plan on deriving classes from the singleton and you want those classes to be singletons, your better choice is monostate. That’s because all classes derived from a monostate are monostates. Classes derived singleton classes are not singletons by default. You would have to add the static method and attribute to each derived class.

Good explanation of ruby object model -- mainly, 'classes are objects'?

I am studying the ruby object model and have some questions. I understand the idea that an object only stores instance variables, and methods are stored in the class, which an object has a reference to. I also understand the idea of 'self' -- what it is, how it changes, etc.
However, what I don't understand is the notion that 'classes are objects.' Is there a good, intuitive explanation anywhere?
(BTW: I'm using Ruby Object Model and Metaprogramming and Metaprogramming Ruby as my two resources. If anybody can suggest something else, that would be helpful.)
Thanks.
It means precisely what it sounds like — classes are objects. Specifically, they are instances of the class Class, which is itself a subclass of the class Module, which in turn is a subclass of Object, just like every other class in Ruby. Like any other object in Ruby, a class can respond to messages, have its own instance variables, etc.
As a practical example, let's take private.
class Person
attr_accessor :name, :height
private
attr_accessor :weight
end
This gives instances of Person public methods to access the person's name and height, but the accessors for the person's weight are private. BUTBUTBUT — rather than being a keyword like in most languages, private is an ordinary method of the Module class. If we wanted, we could redefine it to do something different for a particular class hierarchy.
class RichardStallman
def self.private(*args)
puts "NO! INFORMATION WAS MEANT TO BE FREE!"
end
end
Here's my shot at one.
In Ruby, classes are objects. Usually they have class Class. For example, let's consider the class Foo.
class Foo
end
Doubtless you've seen this before, and it's not terribly exciting. But we could also have defined Foo this way:
Foo = Class.new
Just as you'd create a new Foo by calling Foo.new, you can create a new Class by calling Class.new. Then you give that class the name Foo by assigning it, just like any other variable. That's all there is to it.
The notion of "classes are objects" ( as I understand it ) implies that anything you can do with an object, you can do it with a class.
This differs from other programming languages where the class and the class definition are special artifacts different from objects and often unaccessible to the runtime.
For instance in Ruby, you can modify any object at runtime, since classes are also objects you can modify the class it self and add methods at runtime, delete methods, or add and delete attributes at runtime.
For instance:
$ irb
>> x = Object.new
=> #<Object:0x1011ce560>
>> x.to_s
=> "#<Object:0x1011ce560>"
>> undef to_s
=> nil
>> x.to_s
NoMethodError: undefined method `to_s' for #<Object:0x1011ce560>
from (irb):4
>>
That's not possible on other programming languages where a distinction between objects and classes is made.
note: Probably you should understand basic Ruby concepts before going to meta programming as it may be confusing, that what I would do.
Look at this article, you may find it helpful:
The Ruby Object Model - Structure and Semantics
Personally I learned a lot about the Ruby object model by reading about the Smalltalk one (e.g. in the Squeak documentation). And depending on how fluent you are in C, the MRI sources are quite approachable and yield the most definite answers.
When you think of it, it's completely logical for new to be a function, right? A function which creates and returns a new object. (Unlike most of other languages where new is some kind of operator or a language construct.)
Pushing it further, even more logical for this function new is that it should be a method, if we are talking about an OO language. Whose method? A method of an object, just a little bit different sort of an object that we can call "class".
So, looking it that way, classes are just special kinds of objects, objects that, among other peculiarities, have method new and know how to create other objects based on their own image.
what I don't understand is the notion that 'classes are objects.' Is there a good, intuitive explanation anywhere?
An answer to SO thread `Visual representation of Ruby Object Model' links to an excellent video on the subject.

Resources