Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to dynamically create a subclass of an existing class?

I'm writing Ruby code that creates new classes using Object.const_set, which works great for creating new classes and instantiating instances of them. But I'd like these new classes to inherit from a class I've hardcoded already. I can't find methods to do this. Here's 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
like image 934
Duncan Malashock Avatar asked Oct 11 '13 16:10

Duncan Malashock


1 Answers

Class.new accepts a parameter, which will be the superclass.

Documentation: Class.new.

like image 124
Sergio Tulentsev Avatar answered Feb 04 '23 07:02

Sergio Tulentsev