成功安全的 constantize
User
是 ActiveRecord
或 Mongoid
类。将 User
替换为项目中的任何 Rails
类(甚至类似 Integer
或 Array
)
my_string = "User" # Capitalized string
# => 'User'
my_constant = my_string.safe_constantize
# => User
my_constant.all.count
# => 18
my_string = "Array"
# => 'Array'
my_constant = my_string.safe_constantize
# => Array
my_constant.new(4)
# => [nil, nil, nil, nil]