kid_drew kid_drew - 6 months ago 29
Ruby Question

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

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 (
) using
and use that to call the constant (
), but I know
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?


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

def self.find(id)

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