gjb*_*gjb 3 ruby ruby-on-rails ruby-on-rails-3
我定义@foo为类实例属性,并使用after_initialize回调设置创建/加载记录时的值:
class Blog < ActiveRecord::Base
@foo = nil
after_initialize :assign_value
def assign_value
@foo = 'bar'
end
end
Run Code Online (Sandbox Code Playgroud)
但是,当我inspect是Blog对象时,我没有看到@foo属性:
> Blog.first.inspect
=> "#<Blog id: 1, title: 'Test', created_at: nil, updated_at: nil>"
Run Code Online (Sandbox Code Playgroud)
我需要做些什么inspect来包含这个?或者相反,如何inspect确定输出什么?
谢谢.
活动记录根据数据库表中的列确定要在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
Run Code Online (Sandbox Code Playgroud)
要更改检查的输出,您必须使用自己的方法覆盖它,例如
def inspect
"#{super}, @foo = #{@foo}"
end
Run Code Online (Sandbox Code Playgroud)
哪个应该输出:
> Blog.first.inspect
=> "#<Blog id: 1, title: 'Test', created_at: nil, updated_at: nil>, @foo = 'bar'"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1963 次 |
| 最近记录: |