0

I'm writing a wrapper for a third party REST API using HTTParty. I would like to be able to call the third party API using a call to my local module like this:

APIWrapper::APIObject::APIMethod

I would like to write a magic function inside APIWrapper that accepts the function call and decodes the Object and Method to make a call to the third party API. So the call above would do something like this:

params = {
  'format' = 'json',
  'object' = api_object,
  'method' = api_method,
}

get(APIWrapper::BASE_URI, {:query => params})

I want to be able to populate api_object and api_method automatically based on the method called so I don't have to explicitly write a method for every API call I want to be able to make. In PHP, this would be done using a magic __get method. Is there an equivalent in Ruby?

4

1 回答 1

1

这绝对可以在 Ruby 中完成。你需要const_missing在 APIWrapper 上实现,它会返回一个实现method_missing来获取 API 方法部分的对象:

module APIWrapper
  def const_missing(const_name)
    anon_class = Class.new do
      def method_missing(name, *params, &block)
        params = {
          'format' = 'json',
          'object' = const_name.to_s,
          'method' = name.to_s,
        }
        get(APIWrapper::BASE_URI, {:query => params})
      end
    end
  end
end
于 2013-09-07T20:25:58.740 回答