Wednesday, 11 September 2013

Ruby dynamic constant name access

Ruby dynamic constant name access

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?

No comments:

Post a Comment