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 : un开发者_JS百科defined method 'basename' for class 'File' (NameError)
btw, I'm using JRuby
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
精彩评论