2014-07-24 69 views
0

我使用的是其他客戶,如twitter寶石,redditkitoctokit.rb,才能夠訪問存儲在屬性與attr_readerattr_accessor用戶都使用模型創建API包裝的reddit的樂趣散列。attr_reader紅寶石API包裝

是否有任何標準或原因,爲什麼返回值需要在模型中明確聲明,而不是有一個method_missing從哈希中獲取值?爲什麼它必須是這樣的:

class Something 
    def self.attr_reader(meth) 
    define_method(meth) { @attributes[meth] } 
    end 

    attr_reader :thing1 
    attr_reader :thing2 
    attr_reader :tedium 
    ... 

而不是

class Something 
    def method_missing(meth, args) 
    if @attributes.has_key?(meth) 
     @attributes[meth] 
    else 
     send(:meth, *args) 
    end 
    end 
+0

-1簡單的工作。您對method_missing的定義不合語法。一個方法不能接受符號':meth'作爲變量名(除非是指定參數),並且它不適用於attr讀取器方法,因爲您將傳遞零參數,但期望的參數將是一個。順便說一句,「@ attributes」是什麼?不要在沒有解釋的情況下引入變量。 – sawa

回答

1

attr_reader不通過返回@attributes[:thing],而是返回@thing實現吸氣。使用它是安全的(您只能得到您聲明的內容 - 惡意代碼無法將自己的數據隱藏在對象中等)。

如果你想擁有完全動態屬性的對象,也有它的實現(如OpenStruct),或者您也可以直接與Hash ES ...

+0

這根本不回答OP的問題。這可能最好是一個評論。 – sawa

+0

@sawa OP問題(據我瞭解)是'爲什麼它需要像這樣?'(=因爲它是安全的)'而不是[that]?(=如果這是你所需要的,那就更簡單了選項) –

+0

您的回答「使用安全」? – sawa