Ruby String to Class Name

后端 未结 7 926
感情败类
感情败类 2020-12-24 12:32

I am trying to create a new class to that will inherit from ActiveRecord::Base the class needs to be dynamically generated from a string

\"gener         


        
7条回答
  •  天命终不由人
    2020-12-24 13:10

    Look at this example from "The Book Of Ruby", included in the Ruby 1.9 installer.

    puts("What shall we call this class?> ")
    className = gets.strip().capitalize()
    Object.const_set(className,Class.new)
    puts("I'll give it a method called > 'myname'" ) 
    className = Object.const_get(className)
    className::module_eval{
      define_method(:myname){ 
        puts("The name of my class is '#{self.class}'" ) 
     } }
     x = className.new x.myname
    

提交回复
热议问题