Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

ruby - 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?

If Amber is already a class, I can get from a string to the class via:

Object.const_get("Amber")

or (in Rails)

"Amber".constantize

But either of these will fail with NameError: uninitialized constant Amber if Amber is not already a class.

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"

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...)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about const_defined??

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...