May 09

Overriding class methods in Ruby

Class methods in Ruby are methods that work without being tied to any particular object (Java and PHP5 have static methods for similiar purpose). Class methods are distinguished from instance methods by placing the class name and a period in front of the method name. One thing that may not be obvious if you want to inherit class method is how to call equally named class method from parent class.

Class methods in Ruby are methods that work without being tied to any particular object (Java and PHP5 have static methods for similiar purpose). Class methods are distinguished from instance methods by placing the class name and a period in front of the method name. One thing that may not be obvious if you want to inherit class method is how to call equally named class method from parent class.

If you try to use super.class_method_name it would not work. That’s because class_method_name is class method and not instance method and as such it does not exists in object. Fortunately, classes in Ruby are objects too and you can interact with class like you interact with any other objects.

Enough talking, here is example:


class User
  def User.columns
    "name,email" 
  end
end

class Customer < User
  def Customer.columns
    self.superclass.columns + ",saldo" 
  end
end

puts Customer.columns # << name,email,saldo