2011-03-22 5 views
7

루비에서 클래스 메소드를 재정의하려면 어떻게해야합니까?Ruby - 클래스 메서드를 재정의하는 방법?

예를 들어,이 메서드를 다시 정의하고자합니다. File.basename("C:\abc.txt") 어떻게 처리합니까?

이 작동하지 않습니다

class File 
    alias_method :old_bn, :basename 

    def basename(*args) 
    puts "herro wolrd!" 
    old_bn(*args) 
    end 
end 

은 내가 JRuby

답변

15

alias_method가 인스턴스 메소드위한 것입니다 사용하고, BTW : undefined method 'basename' for class 'File' (NameError)

를 얻을. 그러나 File.basename은 클래스 메소드입니다.

class File 
    class << self 
    alias_method :basename_without_hello, :basename 

    def basename(*args) 
     puts "hello world!" 
     basename_without_hello(*args) 
    end 
    end 
end 

class << self는 "클래스 수준"(Eigenklass)에 대한 모든 평가 - 그래서 당신은 self. (def self.basename)와 alias_method는 클래스 메소드에 적용 작성할 필요가 없습니다.

+2

'class << Foo'의 잘못된 점은 무엇입니까? –

+4

개인 취향. monkey-patch라면'core_ext'에서'class File'을 검색하고 거기서 모든 수정을 찾고 싶습니다. 또한'class << self'라는 단어를 사용하는 것이 더 쉽습니다. 새로운 사람들이 해당 코드에서 작업을 시작하고 아직 그 숙어를 보지 못했다면 그 의미를 알 수 있습니다. –

1
class << File 
    alias_method :old_bn, :basename 
    def basename(f) 
    puts "herro wolrd!" 
    old_bn(*args) 
    end 
end 
관련 문제