Ruby: How to dynamically subclass an existing class?

I am writing Ruby code that creates new classes using Object.const_set, which is great for creating new classes and instance instances. But I would like these new classes to inherit from a class that I already hard-coded. I can not find methods for this. Here is my code:

def create_model_class(klass_name, klass_vars) klass = Object.const_set(klass_name, Class.new) klass.class_eval do define_method(:initialize) klass_vars.each_with_index do |name, i| instance_variable_set("@"+name[i], name[i]) end end end end 
+6
source share
1 answer

Class.new accepts a parameter that will be a superclass.

Documentation: Class.new .

+15
source

Source: https://habr.com/ru/post/955793/


All Articles