如何将字符串转换为类名,但前提是该类已经存在?
如果 Amber 已经是一个类,我可以通过以下方式从字符串获取类:
Object.const_get("Amber")
或(在 Rails 中)
"Amber".constantize
但是,如果 Amber 还不是一个类,它们中的任何一个都会失败并返回 NameError: uninitialized constant Amber
。
我的第一个想法是使用 defined?
方法,但它不区分已经存在的类和不存在的类:
>> defined?("Object".constantize)
=> "method"
>> defined?("AClassNameThatCouldNotPossiblyExist".constantize)
=> "method"
那么在尝试转换字符串之前如何测试它是否命名了一个类? (好吧,用 begin
/rescue
block 来捕获 NameError 错误怎么样?太丑了?我同意...)
最佳答案
const_defined?
怎么样? ?
请记住,在 Rails 中,开发模式下会自动加载,因此在测试时可能会很棘手:
>> 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
关于ruby - 如何检查类是否已定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5758464/