我将@foo
定义为类实例属性,并使用after_initialize
回调设置创建/加载记录时的值:
class Blog < ActiveRecord::Base
@foo = nil
after_initialize :assign_value
def assign_value
@foo = 'bar'
end
end
但是,当我inspect
一个Blog对象时,我没有看到@foo
属性:
> Blog.first.inspect
=> "#<Blog id: 1, title: 'Test', created_at: nil, updated_at: nil>"
要让inspect
包含此内容,我需要做些什么?或者相反,inspect
如何确定要输出的内容?
感谢。
答案 0 :(得分:5)
活动记录根据数据库表中的列确定要在inspect中显示的属性:
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'"