0
我有一个类:有没有办法在Ruby中创建临时名称空间和常量?
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中还是我在做梦?命名空间无污染,临时常量,方法,命名空间,类。干净,专注和优化的代码,没有太多分心。
此链接** **优化**的介绍使得这个答案成为低估的宝石!谢谢 –