Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling super from a class method

Tags:

ruby

When redefining a class method I want to be able to call super, just as I would in a instance method.

For example, I have a class hi with a class method Hi.hi

class Hi
  def self.hi
    puts "hi"
  end
end

Hi.hi #=> "hi"

Now, Lets say i want to redefine self.hi

class Hi
  def self.hi
    super
    puts "Oh!"
  end
end

Hi.hi #=> NoMethodError: super: no superclass method `hi' for Hi:Class

Why doesn't this work?

I know I can get the same functionality using alias (as below), it just seems rather unnecessary.

class Hi
  class << self
    def new_hi
      old_hi
      puts "Oh!"
    end
    alias :old_hi :hi
    alias :hi :new_hi 
  end
end

Hi.hi #=> "hi\n Oh!"

Is there a better way to do this?

like image 849
diedthreetimes Avatar asked Jul 19 '11 20:07

diedthreetimes


1 Answers

Super works for child classes inherited from a parent class.

In your case alias is the only way. Or you can use alias_method:

alias_method :old_hi, :hi

def self.hi
  old_hi
  puts "Oh!"
end
like image 108
Vadim Golub Avatar answered Sep 30 '22 03:09

Vadim Golub