views:

126

answers:

1

I would like to create a virtual attribute that will always be included when you do model_instance.inspect. I understand that attr_reader will give me the same thing as just defining an instance method, but I would like this attribute to be part of the object's "make up"

How can I accomplish this?

Thanks!

UPDATE

Here is what is not working in more detail:

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>

As you can see, when I use the console it returns no "less_secure_asset_url" attribute

A: 

Your attribute is in there, even if it doesn't show up. Rails overrides the definition of the inspect method of Object in ActiveRecord::Base to something like:

  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

Basically, if it's not a column_name, it's not going to show up. I haven't tried this, but you might be able to call something like p.as(Object).inspect to get to the super classes inspect method. You have to require 'facets' to get as. See docs here.

MattMcKnight