听起来您希望 的返回值Myclass::get
是Myclass
. 如果是这种情况,您可以缓存 HTTP 请求的返回值并实现method_missing
从该哈希返回值:
class Myclass
include HTTParty
attr_accessor :retrieved_values
def method_missing(method, *args, &block)
if retrieved_values.key?(method)
retrieved_values[method]
else
super
end
end
def self.get_with_massaging(url)
new.tap do |instance|
instance.retrieved_values = get_without_massaging(url)
end
end
class << self
alias_method :get_without_massaging, :get
alias_method :get, :get_with_massaging
end
end
这不完全是您所要求的,因为它只工作一层深 - 即,x.questions[0].title
需要x.questions[0][:title]
x = Myclass.get('http://api.stackoverflow.com/1.0/questions?tags=HTTParty')
p x.total
p x.questions[0][:title]
也许你可以想出这个答案和 Joshua Creek 的混合体来利用 OpenStruct。
我还应该指出,如果您的方法不必被命名,那么所有方法别名技巧都是不必要的get
。