2010-05-04 56 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