我有一个班级:
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中有这样的东西,还是我只是在做梦?命名空间无污染,临时常量,方法,命名空间,类。清晰,专注和优化的代码,没有太多干扰。