Ruby on Rails
Veilig Constantize
Zoeken…
Succesvolle safe_constantize
User is een ActiveRecord of Mongoid klasse. Vervang User door elke Rails klasse in uw project (zelfs zoiets als Integer of 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]
Niet succesvol safe_constantize
Dit voorbeeld zal niet werken omdat de doorgegeven string niet als een constante in het project wordt herkend. Zelfs als u "array" doorgeeft, werkt het niet omdat het geen hoofdletter is.
my_string = "not_a_constant"
# => 'not_a_constant'
my_string.safe_constantize
# => nil
my_string = "array" #Not capitalized!
# => 'array'
my_string.safe_constantize
# => nil
Modified text is an extract of the original Stack Overflow Documentation
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow