2013-02-27 44 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方法將返回正確的值。