0

私はクラスを持っています:

class MyClass
  def self.say_hello
    puts "hello"
  end
end

クラスとそのメソッドを一時的にオーバーライドするプロセスを作成したいと思います。

begin "a temporary namespace, constants, variables and methods within this code"
  Thread.current[:neverland] = -> do
    Object.instance_exec do
      class MyClass
        def self.say_hi
          puts "hi"
        end
      end

      MyClass.say_hi
      MyClass.say_hello
    end
  end
end

> Thread.current[:neverland].call
=> "hi"
=> "hello"

> MyClass.methods - Object.methods
=> ["say_hello"]

> MyClass.say_hi
=> undefined method `say_hi' for MyClass:Class (NoMethodError)

Ruby にこのようなものはありますか、それとも私は夢を見ているだけですか? 名前空間の無公害、一時定数、メソッド、名前空間、クラス。あまり気を散らすことなく、クリーンで焦点を絞った最適化されたコード。

4

1 に答える 1

1

おそらく、Ruby 2.0 でリリース予定のRefinementsのようなものを考えているでしょう。

それまでは、創造性を発揮する必要があります。

于 2013-01-19T01:34:22.033 に答える