13

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
3
  • 1
    I think the do after define_method has gone awol. It appears that klass_vars is a two-dimensional array. Is that intended? If klass_vars is an just array of strings, I think you need to change each_with_index to each and drop the reference to i. RE @Sergios suggestion, I believe you would add parent_class to the arguments and add (parent_class) to Class.new or add parent_class_name to the arguments and (parent_class_name.to_sym) to Class.new. Commented Oct 11, 2013 at 18:29
  • Hey Cary, klass_vars is a hash. I'm only partway through implementing it so I may be muddying the pool by leaving it in this example code. Thanks for the sharp eye. Commented Oct 11, 2013 at 20:23
  • 1
    A hash, of course. ...but maybe return the errant do. Commented Oct 11, 2013 at 20:28

1 Answer 1

25

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

Documentation: Class.new.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd forgotten about that, Sergio. Thanks for the twig. Much better than eval "class B < A; end"
1. I'm not sure where I'd call Class.new with a parameter – my guess is after I define the constant for the class name? 2. I looked at this lecture and apparently for some things in metaprogramming eval is the only way, although I understand how it can create security issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.