Ruby String to Class Name

后端 未结 7 893
感情败类
感情败类 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:06

    If your string contains a namespace, you can use:

    require 'rubygems'
    require 'active_support/inflector'
    parent=String # using String to get a self contained example
    # require 'active_record'   # uncomment for ActiveRecord::Base as parent class
    # parent=ActiveRecord::Base # uncomment for ActiveRecord::Base as parent class
    namespace = 'A::B::general_systems'.split('::') 
    class_name = namespace.pop 
    namespace = namespace.inject(Object) do |mod, name|
      if mod.constants.collect{|sym| sym.to_s}.include? name.classify
        mod.const_get name.classify
      else
        mod.const_set name.classify, Module.new
      end
    end
    
    klass = if namespace.constants.include? class_name.classify
      namespace.const_get class_name.classify
    else
      namespace.const_set class_name.classify, Class.new(parent)
    end
    
    object = klass.allocate # allocate new object of klass
    object.send :initialize # initialize object
    object.class
    object.class.superclass
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-24 13:15

    Given:

    class Banana
    end
    

    You can fetch the class in plain Ruby with:

    Object.const_get 'Banana'
    => Banana
    

    or if you're using Rails:

    'Banana'.constantize
    => Banana
    
    0 讨论(0)
  • 2020-12-24 13:21

    try

    >> "general_systems".classify
    => "GeneralSystem"
    
    0 讨论(0)
  • 2020-12-24 13:23
    klazz = Class.new(ActiveRecord::Base) do
      def do_something_fun(param1)
        param1.have_fun!
      end
    end
    
    klazz_name = "general_systems".singularize.classify
    Object.const_set(klazz_name, klazz)
    
    0 讨论(0)
  • 2020-12-24 13:28

    If you're using Rails, it provides a method called #constantize that will work:

    irb(main):017:0> Object.const_get 'House::Owns'
    NameError: wrong constant name House::Owns
    
    'House::Owns'.constantize
    => House::Owns
    
    0 讨论(0)
提交回复
热议问题