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