2013-01-19 38 views
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中还是我在做梦?命名空间无污染,临时常量,方法,命名空间,类。干净,专注和优化的代码,没有太多分心。

回答

1

您可能正在考虑计划在Ruby 2.0中发布的类似Refinements的内容。

在此之前,你将不得不有创意。

+0

此链接** **优化**的介绍使得这个答案成为低估的宝石!谢谢 –

相关问题