Ruby syntax abuse
In the Ruby world some habits are becoming very common. Something I see fairly often is the (ab)use of the class << xxx
syntax, which is used to open the singleton class.
Something like this
class Foo
class << self
def bar
puts "Hi!"
end
end
end
Could be written this way:
class Foo
def self.bar
puts "Hi!"
end
end
Isn’t it simpler and more clear? I agree with the nice Metaprogramming Ruby screencasts by Dave Thomas; we should use the <<
syntax only when it simplifies the code, like in this example (taken straight from the second screencast):
class Foo
@x = 0 # Watch out! This is a class variable
class << self
attr_accessor :x
end
end
Foo.x += 1
Similar considerations can be found on this useful post:
http://yehudakatz.com/2009/11/12/better-ruby-idioms/