Cast between String and Classname

前端 未结 3 1955
孤街浪徒
孤街浪徒 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条回答
  •  一生所求
    2020-12-20 08:19

    This solution is better than eval as you are evaluating params hash that might be manipulated by the user and could contain harmful actions. As a general rule: Never evaluate user input directly, that's a big security hole.

    # Monkey patch for String class
        class String
          def to_class
            klass = Kernel.const_get(self)
            klass.is_a?(Class) ? klass : nil
          rescue NameError
            nil
          end
        end
    
    # Examples
    "Fixnum".to_class #=> Fixnum
    "Something".to_class #=> nil
    

    Update - a better version that works with namespaces:

     # Monkey patch for String class
        class String
          def to_class
            chain = self.split "::"
            klass = Kernel
            chain.each do |klass_string|
              klass = klass.const_get klass_string
            end
            klass.is_a?(Class) ? klass : nil
          rescue NameError
            nil
          end
        end
    

提交回复
热议问题