覆盖实例方法

问题描述:

我有两个文件foo和bar。 Foo实现类并初始化实例。内部文件bar.rb我想需要foo.rb而且我想从foo.rb改变实施美孚::酒吧的覆盖实例方法

目录树

  • foo.rb
  • bar.rb

foo.rb

module Foo 
    class Bar 
    def random_method 
     puts "Foo::Bar.random_method" 
    end 
    end 
end 
Foo::Bar.new.random_method 

bar.rb

#here I want overwrite Foo::Bar.random_method 
require_relative 'foo' # so this line use new random_method 
+0

也许先要求然后重写? – 2012-07-20 15:37:29

+0

foo.rb的最后一行将执行方法。所以当我需要这个文件时,它立即将字符串放在屏幕上 – Lewy 2012-07-20 15:43:14

这是不可能的(AFAIK),如果你不允许触摸foo.rb

# bar.rb 

# redefine another random method (to be precise, define its first version) 
module Foo 
    class Bar 
    def random_method 
     puts 'another random method' 
    end 
    end 
end 

require_relative 'foo' # this will redefine the method and execute version from foo.rb 

一种可能的方法是分裂的Foo::Bar声明和使用它的代码。

# foo_def.rb 
module Foo 
    class Bar 
    def random_method 
     puts "Foo::Bar.random_method" 
    end 
    end 
end 

# foo.rb 
require_relative 'foo_def' 
Foo::Bar.new.random_method 

# bar.rb 
require_relative 'foo_def' 

# replace the method here 
module Foo 
    class Bar 
    def random_method 
     puts 'another random method' 
    end 
    end 
end 

require_relative 'foo' # run with updated method