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