How do I redefine a class method in ruby?
say, for example, I want to redefine the method File.basename("C:\abc.txt")
How do I do it?
This doesn't work:
class File
alias_method :old_bn, :basename
def basename(*args)
puts "herro wolrd!"
old_bn(*args)
end
end
I get : undefined method 'basename' for class 'File' (NameError)
btw, I'm using JRuby
Override means two methods having same name but doing different tasks. It means that one of the methods overrides another method. If there is any method in the superclass and a method with the same name in its subclass, then by executing these methods, method of the corresponding class will be executed.
There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2). Both of them have pros and cons.
You could define method in any order, the order doesn't matter anything.
Ruby doesn't treat the ! as a special character at the end of a method name. By convention, methods ending in ! have some sort of side-effect or other issue that the method author is trying to draw attention to.
alias_method
is meant for instance methods. But File.basename
is a class method.
class File
class << self
alias_method :basename_without_hello, :basename
def basename(*args)
puts "hello world!"
basename_without_hello(*args)
end
end
end
The class << self
evaluates everything on the "class level" (Eigenklass) - so you don't need to write self.
(def self.basename
) and alias_method
applies to class methods.
class << File
alias_method :old_bn, :basename
def basename(f)
puts "herro wolrd!"
old_bn(*args)
end
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