Rails 3:如何以可读格式显示对象?

时间:2011-03-22 03:10:54

标签: ruby-on-rails ruby-on-rails-3

显示如下对象:

Job.find(4).inspect

结果:

#<Job id: 4, job_date: "2010-10-22", address: "some address", invoice_number: "b432", client_name: "Fred", client_email: "fred@yahoo.com", client_mobile_number: "12345678", ...>

不太可读。

是否有一种简单的方法来显示这样的对象:

id:                   4
job_date:             "2010-10-22"
address:              "some address"
invoice_number:       "b432"
client_name:          "Fred"
client_email:         "fred@yahoo.com"
client_mobile_number: "12345678"

或其他一些可读方式?

2 个答案:

答案 0 :(得分:2)

不确定您要显示的位置,但对于控制台/调试器,我推荐使用awesome_print gem。

https://github.com/michaeldv/awesome_print

从gem自述文件中打印rails对象示例:

ap Account.all(:limit => 2)
[
    [0] #<Account:0x1033220b8> {
                     :id => 1,
                :user_id => 5,
            :assigned_to => 7,
                   :name => "Hayes-DuBuque",
                 :access => "Public",
                :website => "http://www.hayesdubuque.com",
        :toll_free_phone => "1-800-932-6571",
                  :phone => "(111)549-5002",
                    :fax => "(349)415-2266",
             :deleted_at => nil,
             :created_at => Sat, 06 Mar 2010 09:46:10 UTC +00:00,
             :updated_at => Sat, 06 Mar 2010 16:33:10 UTC +00:00,
                  :email => "info@hayesdubuque.com",
        :background_info => nil
    },
    [1] #<Account:0x103321ff0> {
                     :id => 2,
                :user_id => 4,
            :assigned_to => 4,
                   :name => "Ziemann-Streich",
                 :access => "Public",
                :website => "http://www.ziemannstreich.com",
        :toll_free_phone => "1-800-871-0619",
                  :phone => "(042)056-1534",
                    :fax => "(106)017-8792",
             :deleted_at => nil,
             :created_at => Tue, 09 Feb 2010 13:32:10 UTC +00:00,
             :updated_at => Tue, 09 Feb 2010 20:05:01 UTC +00:00,
                  :email => "info@ziemannstreich.com",
        :background_info => nil
    }
]

答案 1 :(得分:2)

如果您执行raise Job.find(4).to_yaml

,则格式相似