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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With