Cast between String and Classname

前端 未结 3 1958
孤街浪徒
孤街浪徒 2020-12-20 07:39

I have a string, containing an Class name. It is, for example, a string containing \"Article\". That string came up from the params[]. What should I do to work with this str

3条回答
  •  萌比男神i
    2020-12-20 08:36

    class Abc
    end #=> nil
    klass = eval("Abc") #=> Abc
    klass.new #=> #
    

    Assumes there really is a class with the name provided...

    In ActiveSupport, there was String#constantize, which did the same thing, but I believe it's deprecated after 2.1.

    EDIT: this is the implementation of constantize from ActiveSupport 2.1.2:

      def constantize(camel_cased_word)
        names = camel_cased_word.split('::')
        names.shift if names.empty? || names.first.empty?
    
        constant = Object
        names.each do |name|
          constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
        end
        constant
      end
    

提交回复
热议问题