I am writing an internal DSL in Ruby. For this, I need to programmatically create named classes and nested classes. What is the best way to do so? I recon that there are two ways to do so:
- Use
Class.newto create an anonymous class, then usedefine_methodto add methods to it, and finally callconst_setto add them as named constants to some namespace. - Use some sort of
eval
I’ve tested the first way and it worked, but being new to Ruby, I am not sure that putting classes as constants is the right way.
Are there other, better ways? If not, which of the above is preferable?
If you want to create a class with a dynamic name, you’ll have to do almost exactly what you said. However, you do not need to use
define_method. You can just pass a block toClass.newin which you initialize the class. This is semantically identical to the contents ofclass/end.Remember with
const_set, to be conscientious of the receiver (self) in that scope. If you want the class defined globally you will need to callconst_seton the TopLevel module (which varies in name and detail by Ruby).