Informatika Mihelac
May 09 2006 rails | ruby | tips

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.

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
comments feed

4 comments

  1. # On May 16, 2006 at 14:05 PM, zimbatm said:
    It could also be written like that : irb(main):001:0> class User irb(main):002:1> def self.columns irb(main):003:2> "name,email" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> class Customer < User irb(main):007:1> def self.columns irb(main):008:2> super + ",saldo" irb(main):009:2> end irb(main):010:1> end => nil irb(main):011:0> Customer.columns => "name,email,saldo"
  2. # On May 16, 2006 at 14:05 PM, zimbatm said:
    Woops, hope this one is better (what formatting do you use ?) :
    irb(main):001:0> class User
    irb(main):002:1>   def self.columns
    irb(main):003:2>     "name,email"
    irb(main):004:2>     end
    irb(main):005:1>   end
    => nil
    irb(main):006:0> class Customer < User
    irb(main):007:1>   def self.columns
    irb(main):008:2>     super + ",saldo"
    irb(main):009:2>     end
    irb(main):010:1>   end
    => nil
    irb(main):011:0> Customer.columns
    => "name,email,saldo"
    
  3. # On May 16, 2006 at 14:05 PM, zimbatm said:
    damn : http://zimbatm.oree.ch/articles/2006/05/16/ruby-class-method-inheritance
  4. # On May 17, 2006 at 01:05 AM, Bojan said:
    That's even better zimbatm. Ops, I was tempted to write super.columns again :)

Speak your mind:

(Required)

(Required)


(You may use textile in your comments.)

About

I am Bojan Mihelac and this blog is dedicated to share code, thoughts, tools and advices I came up with while working in Informatika Mihelac.

Contact: bmihelac@mihelac.org

RSS feedSubscribe to RSS Feed