如何检查是否定义了类? [英] How do I check if a class is defined?
问题描述
如何将字符串转换为类名,但只有在该类已经存在的情况下才可以。
How do I turn a string into a class name, but only if that class already exists?
如果Amber已经 ,我可以从一个字符串到类通过:
If Amber is already a class, I can get from a string to the class via:
Object.const_get("Amber")
或(在Rails中)
"Amber".constantize
但是其中任何一个都会失败, NameError :未初始化的常量Amber
如果Amber不是一个类。
But either of these will fail with NameError: uninitialized constant Amber
if Amber is not already a class.
我的第一个想法是使用 defined? / code>方法,但它不区分已经存在的类和不存在的类:
My first thought is to use the defined?
method, but it doesn't discriminate between classes that already exist and those that don't:
>> defined?("Object".constantize)
=> "method"
>> defined?("AClassNameThatCouldNotPossiblyExist".constantize)
=> "method"
那么如何测试一个字符串是否命名一个类, (好,一个开始
/ 救援
块捕获NameError错误?
So how do I test if a string names a class before I try to convert it? (Okay, how about a begin
/rescue
block to catch NameError errors? Too ugly? I agree...)
推荐答案
请记住,在Rails中,在开发模式下有自动加载,因此在测试时可能会很棘手:
Remember in Rails, there is auto-loading in development mode, so it can be tricky when you are testing it out:
>> Object.const_defined?('Account')
=> false
>> Account
=> Account(id: integer, username: string, google_api_key: string, created_at: datetime, updated_at: datetime, is_active: boolean, randomize_search_results: boolean, contact_url: string, hide_featured_results: boolean, paginate_search_results: boolean)
>> Object.const_defined?('Account')
=> true
这篇关于如何检查是否定义了类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!