Creating a class dynamically

后端 未结 2 1505
南方客
南方客 2020-12-29 07:43

I\'m trying to create a new class, without knowing the name of the class until it\'s supposed to på created.

Something like this;

    variable = \"V         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 08:04

    Your code would look something akin to this:

    variable = "SomeClassName"
    klass = Class.new(ParentClass)
    # ...maybe evaluate some code in the context of the new, anonymous class
    klass.class_eval {  }
    # ...or define some methods
    klass.send(:title, :Person)
    klass.send(:attribute, :name, String)
    # Finally, name that class!
    ParentClass.send(:const_set, variable, klass)
    

    ...or you could just use eval:

    eval <

提交回复
热议问题