2010-05-04 81 views
0

我想創建一個虛擬屬性,當您執行model_instance.inspect時將始終包含這個屬性。我明白,attr_reader會給我一樣的東西,只是定義一個實例方法,但我希望這個屬性成爲對象的「組成」的一部分如何在Ruby模型中創建只讀虛擬屬性

我該如何做到這一點?

謝謝!

UPDATE

這裏是沒有更詳細的工作:

class Product < ActiveRecord::Base 
    attr_reader :less_secure_asset_url 

    def less_secure_asset_url 
     self.asset.url 
    end 
end 

>> p = Product.find(:all)[1] 
=> #<Product id: 49, asset_file_name: "Etrade_Trade_Conf_Request.docx", asset_content_type: "application/vnd.openxmlformats-officedocument.wordp...", asset_file_size: 38152, asset_updated_at: "2010-05-04 17:45:46", created_at: "2010-05-04 17:45:46", updated_at: "2010-05-04 17:45:46", owner_id: 345, product_type_id: 1> 

正如你可以看到,當我使用它沒有返回 「less_secure_asset_url」 控制檯屬性

+0

@bill brasky,不錯的用戶名:) – 2010-05-04 19:30:03

+0

@macek哈哈謝謝:) – 2010-05-04 19:40:39

+1

問題還不清楚。重寫'#inspect'好嗎?應該'屬性'返回值,等等...... 你想完成什麼? – 2010-05-04 20:02:04

回答

0

你屬性在那裏,即使它沒有出現。軌道覆蓋的ActiveRecord::BaseObjectinspect方法的定義是這樣的:

def inspect 
    attributes_as_nice_string = self.class.column_names.collect { |name| 
     if has_attribute?(name) || new_record? 
     "#{name}: #{attribute_for_inspect(name)}" 
     end 
    }.compact.join(", ") 
    "#<#{self.class} #{attributes_as_nice_string}>" 
    end 

基本上,如果它不是一個列名,它不會顯示出來。我沒有試過這個,但是你可以調用類似p.as(Object).inspect的方法來使用超類檢查方法。你必須require 'facets'得到。請參閱文檔here