2011-05-19 71 views
3

我定義@foo作爲一個類實例的屬性,並使用after_initialize回調來設置這個值創造了一個紀錄時/加載:Rails的:#inspect不顯示屬性

class Blog < ActiveRecord::Base 
    @foo = nil 

    after_initialize :assign_value 

    def assign_value 
    @foo = 'bar' 
    end 
end 

然而,當我inspect博客的對象,我沒有看到@foo屬性:

> Blog.first.inspect 
=> "#<Blog id: 1, title: 'Test', created_at: nil, updated_at: nil>" 

什麼我需要做的就是inspect包含這個?或者相反,inspect如何確定輸出?

謝謝。

回答

5

活動記錄確定哪些屬性顯示在基於數據庫表中的列檢查:從base.rb on github

提升到更改檢查你的輸出

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

將有覆蓋它你自己的方法,例如

def inspect 
    "#{super}, @foo = #{@foo}" 
end 

應該輸出:

> Blog.first.inspect 
=> "#<Blog id: 1, title: 'Test', created_at: nil, updated_at: nil>, @foo = 'bar'" 
+0

另外,我認爲你不能與方法參考符號調用after_initialize,你必須明確地創建一個名爲after_initialize(如:'高清after_initialize方法; @foo ='bar'; end') – 2011-05-19 17:10:38

+0

覆蓋正是我正在嘗試與tryruby(該死的,這是一個麻煩)。謝謝你的發佈:D – 2011-05-19 17:11:02

+0

完美,謝謝。我不知道Rails覆蓋了Ruby檢查方法。 – gjb 2011-05-19 19:28:20