22

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?

4

1 回答 1

44

我想你正在寻找const_get. 也许是这样的:

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

(注意你只需要self.name,因为这已经在类的上下文中,并且self.class.name只是Class)。

于 2013-09-11T23:46:27.060 回答