I am creating non-namespaced classes dynamically.
I have seen an example where this creation is done within the Object class:
class Object
for elem in ARRAY
sub_class = Object.const_set(elem.to_s.camelize, Class.new(SuperClass))
sub_class.class_eval do
def initialize(*args, &block)
...
super *args, &block
end
end
end
end
My Questions:
- Would you also evaluate this within the context of Object?
- Where is the difference from creating classes in global namespace?
- Any advantages or disadvantages?
Interesting. Upon some experimentation, calling
SomeConstant.const_setfrom different contexts doesn’t make any difference, so calling it inside theclass Objectblock is the same as defining it in the toplevel namespace.Furthermore: everything in the global namespace is implicitely defined in the Object class, so it is actually redundant. The only advantage I can see [over defining it in a different class, or in the Kernel module] is that the constant will be available to all classes, and the lookup chain will look at the
Objectclass before theKernelmodule.