ruby convert class name in string to actual class

后端 未结 6 1786
后悔当初
后悔当初 2020-12-12 20:03

How do I call a class from a string containing that class name inside of it? (I guess I could do case/when but that seems ugly.)

The reason I ask is because I\'m us

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 20:43

    If you want to convert string to actuall class name to access model or any other class

    str = "group class"
    
    > str.camelize.constantize 'or'
    > str.classify.constantize 'or'
    > str.titleize.constantize
    
    Example :
      def call_me(str)
        str.titleize.gsub(" ","").constantize.all
      end
    
    Call method : call_me("group class")
    
    Result:
      GroupClass Load (0.7ms) SELECT `group_classes`.* FROM `group_classes`
    

提交回复
热议问题