2013-02-27 49 views
0

我正在为ruby中的外部服务创建api包装器。我使用HTTParty,我期待的回应可以像任何一种格式:api包装器必须处理可变响应

response = {one: two:{three:{four: {five: "hello there"}}}} 
response = {one: two:{three:{four: {five: ["hello there", "good by now"]}}}} #notice array 
response = {one: two:{three:{four: {five: six:{seven: {eight: {nine:{ten: "wow, ugly"}}}}}}}} 
response = {one: "bad response"} 
response = {one: two:[{three:{four: {five: "hello there"}}}, "check here too"]} 

我已经创造了许多if else检查。请记住one,two等......不是真正的关键名称。真正的钥匙名称更像FirstBusinessType,CommercialPropertyLocationAddress1。所以,所有这些都会导致我的屏幕充满长长的丑角。我如何将它全部抽象到另一个课堂或一个对象中?有没有我应该看看你可以推荐的教程? Github API封装(如Twitter)看起来不错。我几乎看不到任何关键或这种性质的条件。如何让我的代码看起来像ruby,而不是像api的响应?

感谢

回答

0

这听起来像你需要做一个演讲类,它可以解释收到的各种格式,为您提供了一个一致的API在那里与价值观的接口。

在实践中,这可能看起来像:

response = ResponsePresenter.new(arbitrary_hash) 
response.business 
response.locations.each do |location| 
    # ... 
end 

主讲模型负责搞清楚是在扮演怎样的格式和配置本身,以便像business方法将返回正确的值。