Presentation of ruby/rails objects?

When viewing an Active Record object in Rails (ex. Foo.find(1) ) in the console, you get back something like:

=> #<Foo id: 1, name: "Far">

which shows the model name and each active record field from the database, without showing the same @instance variables, which in this case would be @far=.

How can I get the same representation for regular class objects, which instead return, with name defined as an attr_accessor:

=> #<Foo:0x00000102fbf970 @name="Far">

The reason why I want this is to be able to see the values for a set of methods on a class, instead of only seeing the attr_accessor (or attr_reader) method variables.

Is there a method that defines what the output of an object is?


The output in irb is done by calling Object#inspect which in turn calls Object#to_s . You can override either one of these. I tend to think of inspect as the debug view, and to_s as the standard user display.

class Foo
  attr_accessor :bar, :value

  def to_s
    @value
  end

  def inspect
    "bar: #{@bar}, value: #{@value}"
  end
end

YMMV

链接地址: http://www.djcxy.com/p/25730.html

上一篇: 为什么我们需要attr

下一篇: 介绍ruby / rails对象?