kid_drew
kid_drew

Reputation: 3995

Get Ruby class constant dynamically by name

I have a class API that pulls objects from a third party API and builds them into objects that are subclasses of type APIObject. APIObject subclasses match the object names from the API that I'm pulling from:

User < APIObject
Account < APIObject

I would like to define a class method in APIObject that allows me to pull objects using standard Rails accessors:

user = User.find id

I would like the method to translate this call into an API call like this:

API::User::findById id

I would like to access the name of the APIObject subclass (User) using self.class.name and use that to call the constant (API::User), but I know API::self.class.name won't work. I could rewrite this method over and over again for every subclass, but it seems like this should be possible without doing that. Suggestions?

Upvotes: 24

Views: 15425

Answers (1)

matt
matt

Reputation: 79723

I think you’re looking for const_get. Perhaps something like:

def self.find(id)
  API.const_get(self.name).find_by_id(id)
end

(note you only need self.name, since this is already in the context of the class, and self.class.name will just be Class).

Upvotes: 46

Related Questions