Ruby-on-rails 如何在 Rails 中打印出对象的内容以便于调试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4829909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:14:05  来源:igfitidea点击:

How do I print out the contents of an object in Rails for easy debugging?

ruby-on-railsruby

提问by cjm2671

I think I'm trying to get the PHP equivalent of print_r()(print human-readable); at present the raw output is:

我想我正在尝试获得相当于print_r()(打印人类可读)的 PHP ;目前原始输出是:

ActiveRecord::Relation:0x10355d1c0

What should I do?

我该怎么办?

回答by jerhinesmith

I generally first try .inspect, if that doesn't give me what I want, I'll switch to .to_yaml.

我通常先尝试.inspect,如果那不能给我想要的,我会切换到.to_yaml.

class User
  attr_accessor :name, :age
end

user = User.new
user.name = "John Smith"
user.age = 30

puts user.inspect
#=> #<User:0x423270c @name="John Smith", @age=30>
puts user.to_yaml
#=> --- !ruby/object:User
#=> age: 30
#=> name: John Smith

Hope that helps.

希望有帮助。

回答by Chris Ledet

define the to_s method in your model. For example

在模型中定义 to_s 方法。例如

class Person < ActiveRecord::Base
  def to_s
    "Name:#{self.name} Age:#{self.age} Weight: #{self.weight}"
  end
end

Then when you go to print it with #puts it will display that string with those variables.

然后,当您使用 #puts 打印它时,它将显示带有这些变量的字符串。

回答by ljouglar

I'm using the awesome_print gem

我正在使用awesome_print gem

So you just have to type :

所以你只需要输入:

ap @var

回答by Papouche Guinslyzinho

In Rails you can print the result in the View by using the debug' Helper ActionView::Helpers::DebugHelper

在 Rails 中,您可以使用调试的 Helper ActionView::Helpers::DebugHelper在视图中打印结果

#app/view/controllers/post_controller.rb
def index
 @posts = Post.all
end

#app/view/posts/index.html.erb
<%= debug(@posts) %>

#start your server
rails -s

results (in browser)

结果(在浏览器中)

- !ruby/object:Post
  raw_attributes:
    id: 2
    title: My Second Post
    body: Welcome!  This is another example post
    published_at: '2015-10-19 23:00:43.469520'
    created_at: '2015-10-20 00:00:43.470739'
    updated_at: '2015-10-20 00:00:43.470739'
  attributes: !ruby/object:ActiveRecord::AttributeSet
    attributes: !ruby/object:ActiveRecord::LazyAttributeHash
      types: &5
        id: &2 !ruby/object:ActiveRecord::Type::Integer
          precision: 
          scale: 
          limit: 
          range: !ruby/range
            begin: -2147483648
            end: 2147483648
            excl: true
        title: &3 !ruby/object:ActiveRecord::Type::String
          precision: 
          scale: 
          limit: 
        body: &4 !ruby/object:ActiveRecord::Type::Text
          precision: 
          scale: 
          limit: 
        published_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
          subtype: &1 !ruby/object:ActiveRecord::Type::DateTime
            precision: 
            scale: 
            limit: 
        created_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
          subtype: *1
        updated_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
          subtype: *1

回答by William Hampshire

.inspectis what you're looking for, it's way easier IMO than .to_yaml!

.inspect就是您要找的东西,IMO 比.to_yaml!

user = User.new
user.name = "will"
user.email = "[email protected]"

user.inspect
#<name: "will", email: "[email protected]">

回答by zee

pp does the job too, no gem requiring is required.

pp 也可以完成这项工作,不需要 gem。

@a = Accrual.first ; pp @a

#<Accrual:0x007ff521e5ba50
 id: 4,
 year: 2018,
 Jan: #<BigDecimal:7ff521e58f08,'0.11E2',9(27)>,
 Feb: #<BigDecimal:7ff521e585d0,'0.88E2',9(27)>,
 Mar: #<BigDecimal:7ff521e58030,'0.0',9(27)>,
 Apr: #<BigDecimal:7ff521e53698,'0.88E2',9(27)>,
 May: #<BigDecimal:7ff521e52fb8,'0.8E1',9(27)>,
 June: #<BigDecimal:7ff521e52900,'0.8E1',9(27)>,
 July: #<BigDecimal:7ff521e51ff0,'0.8E1',9(27)>,
 Aug: #<BigDecimal:7ff521e51bb8,'0.88E2',9(27)>,
 Sep: #<BigDecimal:7ff521e512f8,'0.88E2',9(27)>,
 Oct: #<BigDecimal:7ff521e506c8,'0.0',9(27)>,
 Nov: #<BigDecimal:7ff521e43d38,'0.888E3',9(27)>,
 Dec: #<BigDecimal:7ff521e43478,'0.0',9(27)>,

You can also print two instances of an object:

您还可以打印一个对象的两个实例:

 pp( Accrual.first , Accrual.second)
`
`
`

回答by thisismydesign

inspectis great but sometimes not good enough. E.g. BigDecimalprints like this: #<BigDecimal:7ff49f5478b0,'0.1E2',9(18)>.

inspect很棒,但有时还不够好。例如,BigDecimal打印这样的:#<BigDecimal:7ff49f5478b0,'0.1E2',9(18)>

To have full control over what's printed you could redefine to_sor inspectmethods. Or create your own one to not confuse future devs too much.

要完全控制打印的内容,您可以重新定义to_sinspect方法。或者创建自己的一个,以免混淆未来的开发人员。

  class Something < ApplicationRecord

    def to_s
      attributes.map{ |k, v| { k => v.to_s } }.inject(:merge)
    end

  end

This will apply a method (i.e. to_s) to all attributes. This example will get rid of the ugly BigDecimals.

这将对to_s所有属性应用一个方法(即)。这个例子将摆脱丑陋的BigDecimals.

You can also redefine a handful of attributes only:

您还可以仅重新定义少数属性:

  def to_s
    attributes.merge({ my_attribute: my_attribute.to_s })
  end

You can also create a mix of the two or somehowadd associations.

您还可以创建两者的混合或以某种方式添加关联。

回答by Andrew

You need to use debug(@var). It's exactly like "print_r".

您需要使用debug(@var). 它就像“print_r”。