Are there simple ways to reshuffle namespaces?
Consider file foo.rb with this code:
class Foo
end
Let’s assume someone else wrote this code, so I can not
easily modify it.
Can I put it into a namespace upon load-time, or lateron?
Consider the same code, but put in a module or a class.
Is there a way for me to reshuffle this into another namespace?
For instance, if I don’t like a top namespace as class, I’d like to have
the option to put it into a module forcibly.
Example:
class Bar
class Foo
end
end
Otherwise, same code as above.
And of course the last example:
module Bar
class Foo
end
end
quik77
2
Robert H. wrote in post #1153580:
Are there simple ways to reshuffle namespaces?
Consider file foo.rb with this code:
class Foo
end
Let’s assume someone else wrote this code, so I can not
easily modify it.
- Can I put it into a namespace upon load-time, or lateron?
And of course the last example:
module Bar
class Foo
end
end
Because a module is a namespace, question #1 and #3 are the same:
#foo.rb ------
class Foo
def greet
puts ‘hello’
end
end
#-----------
A = Module.new
code = File.read(‘foo.rb’)
A.module_eval(code)
A::Foo.new.greet
Foo.new.greet
–output:–
hello
1.rb:5:in `’: uninitialized constant Foo (NameError)
Example:
class Bar
class Foo
end
end
A = Class.new
code = File.read(‘foo.rb’)
A.class_eval(code)
class A
Foo.new.greet
end
Foo.new.greet
–output:–
hello
1.rb:9:in `’: uninitialized constant Foo (NameError)