【问题标题】:Overwriting instance method覆盖实例方法
【发布时间】:2012-07-19 21:57:51
【问题描述】:

我有两个文件 foo 和 bar。 Foo 实现类并初始化实例。在 bar.rb 文件中,我需要 foo.rb,但我也想从 foo.rb 更改 Foo::Bar 的实现

目录树

  • 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

【问题讨论】:

  • 可能先需要再覆盖?
  • foo.rb 的最后一行将执行方法。所以当我需要这个文件时,它会立即将字符串放在屏幕上

标签: ruby metaprogramming


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-01-04
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    相关资源
    最近更新 更多