开发者

Ruby - How to redefine class methods?

开发者 https://www.devze.com 2023-02-19 09:25 出处:网络
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?

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
0

精彩评论

暂无评论...
验证码 换一张
取 消