어떻게 하지 않고 기업 재정의 클래스 메소드를 호출에서 원본에서는 새로운 방법이 있나요?

StackOverflow https://stackoverflow.com/questions/288020

문제

내가 발견 중 하나는 원본으로 구성되어 있다는 사실을 무시 Time.strftime 다음과 같다:

class Time
  alias :old_strftime :strftime
  def strftime
    #do something
    old_strftime
  end
end

문제입니다, strftime 인스턴스 방법이다.해 재정의 Time.now -클래스 메소드에서는 모든 발신자가 내는 새로운 방식,새로운 방법을 아직도 원 .now 방법입니다.나는 보았 alias_method 과 만난다.

도움이 되었습니까?

해결책

이것은 좀 하드 주위에 당신의 머리를 얻기 위해 때로는,그러나 당신이 필요하려면"eigenclass"는 단일 관련된 특정 클래스 개체입니다.이 구문은 다음과 같습니다 클래스 << 셀프 할...end.

class Time
  alias :old_strftime :strftime

  def strftime
    puts "got here"
    old_strftime
  end
end

class Time
  class << self
    alias :old_now :now
    def now
      puts "got here too"
      old_now
    end
  end
end

t = Time.now
puts t.strftime

다른 팁

클래스 메소드는 방법이 있습니다.나는 추천에 대한 이지만,당신은 두 가지에 해당 선택:

class Time
  class << self
    alias_method :old_time_now, :now

    def now
      my_now = old_time_now
      # new code
      my_now
    end
  end
end

class << Time
  alias_method :old_time_now, :now

  def now
    my_now = old_time_now
    # new code
    my_now
  end
end

는 경우를 재정의해야 합니다 그것은 테스트를 위한 목적으로(그 이유는 내가 정상적으로 재정의하려는 시간입니다.지금),루비를 조롱/스텁 프레임워크에 대해 이렇게 당신은 쉽습니다.예를 들면,RSpec(을 사용하는 flexmock):

Time.stub!(:now).and_return(Time.mktime(1970,1,1))

그런데,나는 추천을 피하는 필요하 stub 아웃 시간입니다.지금 당신의 클래스는 재정의할 수 있는 시계:

class Foo
  def initialize(clock=Time)
    @clock = clock
  end

  def do_something
    time = @clock.now
    # ...
  end
end

내가 하려고 했는데 어떻게 재정의 인스턴스 메서드를 사용하여 모듈을 사용합니다.

module Mo
  def self.included(base)
    base.instance_eval do
      alias :old_time_now :now
      def now
        my_now = old_time_now
        puts 'overrided now'
        # new code
        my_now
      end
    end
  end
end
Time.send(:include, Mo) unless Time.include?(Mo)

> Time.now
overrided now
=> Mon Aug 02 23:12:31 -0500 2010
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top