0

model_instance.inspect を実行するときに常に含まれる仮想属性を作成したいと思います。attr_reader が単にインスタンス メソッドを定義するのと同じ結果をもたらすことは理解していますが、この属性をオブジェクトの「構成」の一部にしたいと考えています。

どうすればこれを達成できますか?

ありがとう!

アップデート

これは、より詳細に機能していないものです。

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」属性が返されません

4

1 に答える 1

0

表示されなくても、属性はそこにあります。Rails はinのinspectメソッドの定義を次のようにオーバーライドします。ObjectActiveRecord::Base

  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

基本的に column_name でなければ表示されません。p.as(Object).inspect私はこれを試していませんが、スーパークラスの inspect メソッドにアクセスするようなものを呼び出すことができるかもしれません。あなたはrequire 'facets'として取得する必要があります。こちらのドキュメントを参照してください。

于 2010-05-05T03:36:17.150 に答える