0

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

Bill Brasky
  • 201
  • 1
  • 3
  • 13
  • @bill brasky, nice username :) – maček May 04 '10 at 19:30
  • 1
    Question is unclear. Is overriding `#inspect` ok? Should `attributes` return that value, etc... What are you trying to accomplish? – Marc-André Lafortune May 04 '10 at 20:02
  • When I get an object - p = Product.find(:all)[0], I want the product to include certain attributes that are not in the database but should be in the object. Therefore, overriding inspect is not acceptable. – Bill Brasky May 04 '10 at 20:24

1 Answers1

0

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
  • 8,185
  • 28
  • 35