2

I'm working with a Grape API and I have models which have a url attribute that I'm using to dynamically mount endpoints for. I need to be able to version them and I'm having trouble getting them to be properly namespaced when they're generated.

If I create a class within a module, that class is namespaced.

module MyModule
  module SubModule
    class MyClass
    end
  end
end
=> nil 
MyModule::SubModule::MyClass
=> MyModule::SubModule::MyClass 

However, if I dynamically, create the class within a module, it isn't namespaced.

module MyModule
  module SubModule
    dynamic_name = "ClassName"
    Object.const_set(dynamic_name, Class.new)
  end
end
=> ClassName 
MyModule::SubModule::ClassName
NameError: uninitialized constant MyModule::SubModule::ClassName
ClassName
=> ClassName 

Is there a way to namespace a dynamically created class?

Joshua Hunter
  • 4,248
  • 2
  • 12
  • 13

1 Answers1

3

Object.const_set explicitly sets the constant in the Object namespace, which is the root namespace. If you use const_set without Object, it will set the constant in whatever the current namespace is, which is MyModule::SubModule in your example.

dtroof
  • 211
  • 2
  • 8