gjb
gjb

Reputation: 6317

Rails: #inspect not displaying attribute

I am defining @foo as a class instance attribute, and using the after_initialize callback to set the value of this when a record is created/loaded:

class Blog < ActiveRecord::Base
  @foo = nil

  after_initialize :assign_value

  def assign_value
    @foo = 'bar'
  end
end

However, when I inspect a Blog object, I am not seeing the @foo attribute:

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

What do I need to do to get inspect to include this? Or conversely, how does inspect determine what to output?

Thanks.

Upvotes: 3

Views: 2546

Answers (1)

Chris Bailey
Chris Bailey

Reputation: 4136

Active record determines which attributes to show in inspect based on the columns in the database table:

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

Lifted from base.rb on github

To change the output of inspect you'll have to overwrite it with your own method e.g.

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

Which should output:

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

Upvotes: 5

Related Questions