0

是否可以让 HTTParty 将 GET 的结果反序列化为强类型的 ruby​​ 对象?例如

class Myclass
 include HTTParty

end

x = Myclass.get('http://api.stackoverflow.com/1.0/questions?tags=HTTParty')

puts x.total
puts x.questions[0].title

现在它将它反序列化为哈希

puts x["total"]

我的问题实际上是 HTTParty 是否支持这个 OTB,而不是通过安装额外的 gem。

编辑

我还是 Ruby 的新手,但我记得类字段都是私有的,因此需要通过 getter/setter 方法访问它们。所以也许这个问题不是一个有效的问题?

4

2 回答 2

2

如果您只需要方法语法,则可以使用开放结构。

require 'httparty'
require 'ostruct'

result = HTTParty.get 'http://api.stackoverflow.com/1.0/questions?tags=HTTParty'
object = OpenStruct.new result
object.total # => 2634237

一个可能的缺点是这个对象是完全开放的,所以如果你在它上面调用一个不存在的方法,它只会返回 nil(如果你调用一个 setter,它会同时创建 setter 和 getter)

于 2012-02-10T00:32:17.390 回答
1

听起来您希望 的返回值Myclass::getMyclass. 如果是这种情况,您可以缓存 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

于 2012-02-10T01:34:05.910 回答