Is there a way to create temporary namespaces and constants in Ruby?-Collection of common programming errors
I have a class:
class MyClass
def self.say_hello
puts "hello"
end
end
and I want to create a process to override the class and its method temporarily:
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)
Is there something like this in Ruby or am I just dreaming? Namespace pollution-free, temporary constants, methods, namespace, class. Clean, focused and optimized code, without too much distractions.
Originally posted 2013-11-09 23:22:01.