alphagov/whitehall — pull request #834 by gma (2013-09-10 13:54:38+00:00)
Title: Don't use `class << self` to define class methods

Many people define their class methods by opening up the current class's meta class, changing the value of self within the block to be the meta class, and then defining instance methods on the meta class.

If you don't follow that description, you'll recognise the syntax:

class << self
def foo
'oh god!'
end
end

There are two problems with this:

1. You can't grep for class methods (e.g. for /def self.thing/).

2. You can't tell whether a method is a class method when you're reading the code, unless you're fortunate enough for both a) `class << self` to be visible in your editor window, and b) to have actually noticed it (it could be some distance away).

In other words, it's obfuscation.

I propose we stop doing this, and always say `def self.foo` instead.

Dave Thomas agrees, and says "I think it's a really bad habit to fall into ... my strong recommendation is that you don't use `class << self` if all you're doing is defining class methods." That quote is from episode 2 of [The Ruby Object Model and Metaprogramming][video]; start watching from 17m 10s in.

There are a few occassions that `class << self` is useful, and Dave shows you some examples in the video.

[video]: http://pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming