How do I check if a class is defined? How do I check if a class is defined? ruby ruby

How do I check if a class is defined?


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


In rails it's really easy:

amber = "Amber".constantize rescue nilif amber # nil result in false    # your code hereend


Inspired by @ctcherry's response above, here's a 'safe class method send', where class_name is a string. If class_name doesn't name a class, it returns nil.

def class_send(class_name, method, *args)  Object.const_defined?(class_name) ? Object.const_get(class_name).send(method, *args) : nilend

An even safer version which invokes method only if class_name responds to it:

def class_send(class_name, method, *args)  return nil unless Object.const_defined?(class_name)  c = Object.const_get(class_name)  c.respond_to?(method) ? c.send(method, *args) : nilend