Creating a class at runtime in a module / namespace

Creating a class at runtime is as follows:

klass = Class.new superclass, &block Object.const_set class_name, klass 

Example:

 class Person def name "Jon" end end klass = Class.new Person do def name "#{super} Doe" end end Object.const_set "Employee", klass puts Employee.new.name # prints "Jon Doe" 

Now let's say that you have a module called "Company":

 module Company end 

How do you create an Employee class at runtime inside the Company Company module / space, so that the following gives the same result?

 puts Company::Employee.new.name # prints "Jon Doe" 
+4
source share
2 answers

Easier than you think :)

 Company.const_set "Employee", klass 

When you set something on an Object , it becomes global, because, well, it's all an Object . But you can do const_set for each class / module. And remember that modules / classes are just constants. So Company::Employee is the Employee constant in the Company constant. It's simple:)

Full code:

 class Person def name "Jon" end end klass = Class.new Person do def name "#{super} Doe" end end module Company end Company.const_set "Employee", klass Company::Employee.new.name # => "Jon Doe" 
+12
source

You already had all the necessary things:

 class Person def name "Jon" end end klass = Class.new Person do def name "#{super} Doe" end end module Company end Company.const_set "Employee", klass puts Company::Employee.new.name # prints "Jon Doe" Company.constants.grep(/Emp/) #=> [:Employee] 
+2
source

All Articles