Dynamically define named classes in Ruby

Viewed 13348

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:

  1. Use Class.new to create an anonymous class, then use define_method to add methods to it, and finally call const_set to add them as named constants to some namespace.
  2. 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?

3 Answers
Related