2011-04-13 68 views
0

我正在使用來自第三方API的JSON數據,對該數據執行一些處理,然後將模型作爲JSON發送到客戶端。傳入數據的密鑰沒有很好地命名。其中一些是首字母縮略詞,一些似乎是隨機字符。例如:重命名ActiveResource屬性

{ 
    aikd: "some value" 
    lrdf: 1 // I guess this is the ID 
} 

我創建一個軌道的ActiveResource模型來包裝這個資源,但不希望通過model.lrdf訪問這些屬性,它不是明顯的真的是什麼LRDF!相反,我想以某種方式將這些屬性別名爲另一個更好命名的屬性。有些東西讓我可以說model.id = 1並讓lrdf自動設置爲1或放入model.id並讓它自動返回1.另外,當我調用model.to_json將模型發送給客戶端時,我不想要我的JavaScript必須理解這些奇怪的命名約定。

我試圖

alias id lrdf 

但是這給了我一個錯誤說LRDF是不存在的方法。

另一種選擇是隻包住屬性:

def id 
    lrdf 
end 

這個工作,但是當我打電話model.to_json,我再次看到LRDF的鑰匙。

有沒有人做過這樣的事情?你有什麼建議?

回答

1

你有沒有嘗試過一些before_save魔法?也許你可以定義attr_accessible:ldrf,然後在before_save過濾器中,將ldrf分配給你的id字段。還沒有嘗試過,但我認爲它應該起作用。

attr_accessible :ldrf 

before_save :map_attributes 

protected 
    def map_attributes 
    {:ldrf=>:id}.each do |key, value| 
     self.send("#{value}=", self.send(key)) 
    end 
    end 

讓我知道!

+0

我認爲這可以用於保存,但在我的情況下,數據是隻讀的,所以我只關心在讀取時轉換它。 – Brad 2011-04-13 21:08:53

+0

我最終做了類似的地方,我重寫了ActiveResource :: Base的加載方法。 – Brad 2011-05-23 15:57:18

0

您可以嘗試創建基於ActiveResource :: Formats :: JsonFormat的格式化程序模塊並覆蓋decode()。如果你必須更新數據,你必須重寫encode()。查看當地的gems/activeresource-N.N.N/lib/active_resource/formats/json_format.rb以查看原始json格式化程序的功能。

如果您的模型名稱是Model並且您的格式化程序是CleanupFormatter,那麼只需執行Model.format = CleanupFormatter。

module CleanupFormatter 
    include ::ActiveResource::Formats::JsonFormat 
    extend self 
    # Set a constant for the mapping. 
    # I'm pretty sure these should be strings. If not, try symbols. 
    MAP = [['lrdf', 'id']] 

    def decode(json) 
    orig_hash = super 
    new_hash = {} 
    MAP.each {|old_name, new_name| new_hash[new_name] = orig_hash.delete(old_name) } 
    # Comment the next line if you don't want to carry over fields missing from MAP 
    new_hash.merge!(orig_hash) 
    new_hash 
    end 
end 

這不涉及別名,你問過,但我認爲它有助於隔離模型中的亂碼名字,就永遠不會知道這些原始名稱存在。 「to_json」將顯示可讀的名稱。