Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Ruby class constant dynamically by name

Tags:

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?

like image 481
kid_drew Avatar asked Sep 11 '13 22:09

kid_drew


1 Answers

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

like image 76
matt Avatar answered Oct 13 '22 20:10

matt