2012-07-20 193 views
0

我有兩個文件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

回答

2

這是不可能的(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