views:

35

answers:

1

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?
+2  A: 

Interesting. Upon some experimentation, calling SomeConstant.const_set from different contexts doesn't make any difference, so calling it inside the class Object block 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 Object class before the Kernel module.

Chubas
Ah, okay.Regarding your last sentence: my question was whether defining it in `Object` is advantageous compared to toplevel namespace. So it will be available to all classes anyway. Thus, the bottom line is: *There is no difference* (as global namespace means implictly Object namespace).
duddle