Ruby / Ruby on Rails 中是否有 print_r 或 var_dump 等价物?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/904314/
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-02 21:16:52  来源:igfitidea点击:

Is there a print_r or var_dump equivalent in Ruby / Ruby on Rails?

ruby-on-railsruby

提问by Daniel Rikowski

I'm looking for a way to dump the structure of an object, similar to the PHP functions print_rand var_dumpfor debugging reasons.

我正在寻找一种转储对象结构的方法,类似于 PHP 函数print_rvar_dump出于调试原因。

回答by dbr

The .inspectmethod of any object should format is correctly for display, just do..

.inspect任何对象的方法都应该正确格式化以进行显示,只需执行..

<%= theobject.inspect %>

The .methodsmethod may also be of use:

.methods方法也可能有用:

<%= theobject.methods.inspect %>

It may help to put that in <pre>tags, depending on the data

<pre>根据数据,将其放入标签可能会有所帮助

回答by Artem Russakovskii

In views:

在视图中:

include DebugHelper

...your code...

debug(object)

In controllers, models, and other code:

在控制器、模型和其他代码中:

puts YAML::dump(object)

Source

来源

回答by ujh

In a view you can use <%= debug(yourobject) %>which will generate a YAML view of your data. If you want something in your log you should use logger.debug yourobject.inspect.

在视图中,您可以使用<%= debug(yourobject) %>它将生成数据的 YAML 视图。如果你想在你的日志中添加一些东西,你应该使用logger.debug yourobject.inspect.

回答by Marcin Urbanski

You can also use YAML::dumpshorthand (y) under Rails console:

您还可以在 Rails 控制台下使用YAML::dump简写(y):

>> y User.first
--- !ruby/object:User 
attributes: 
  created_at: 2009-05-24 20:16:11.099441
  updated_at: 2009-05-26 22:46:29.501245
  current_login_ip: 127.0.0.1
  id: "1"
  current_login_at: 2009-05-24 20:20:46.627254
  login_count: "1"
  last_login_ip: 
  last_login_at: 
  login: admin
attributes_cache: {}

=> nil
>> 

If you want to just preview some string contents, try using raise(for example in models, controllers or some other inaccessible place). You get the backtrace for free:)

如果您只想预览一些字符串内容,请尝试使用raise(例如在模型、控制器或其他一些无法访问的地方)。您可以免费获得回溯:)

>> raise Rails.root
RuntimeError: /home/marcin/work/github/project1
    from (irb):17
>> 

I also really encourage you to try ruby-debug:

我也真的鼓励你尝试ruby-debug

It's incredibly helpful!

它非常有帮助!

回答by Trantor Liu

You can use puts some_variable.inspect. Or the shorter version: p some_variable. And for prettier output, you can use the awesome_print gem.

您可以使用puts some_variable.inspect. 或者更短的版本:p some_variable. 对于更漂亮的输出,您可以使用awesome_print gem

回答by Papouche Guinslyzinho

Prrevious answers are great but if you don't want to use the console (terminal), in Rails you can print the result in the View by using the debug's 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 Mikoangelo

If you just want the relevant data to be displayed to stdout (the terminal output if you're running from the command line), you can use p some_object.

如果您只想将相关数据显示到标准输出(如果您从命令行运行,则为终端输出),您可以使用p some_object.

回答by Pawel Barcik

I use this :)

我用这个:)

require 'yaml'

module AppHelpers
  module Debug
    module VarDump

      class << self

        def dump(dump_object, file_path)
          File.open file_path, "a+" do |log_file|
            current_date = Time.new.to_s + "\n" + YAML::dump(dump_object) + "\n"
            log_file.puts current_date
            log_file.close
          end
        end

      end

    end
  end
end

回答by Daniel Rikowski

Lately I'm using awesome_print's apmethod which works on the console as well as in views.

最近,我使用了awesome_printap方法,该方法适用于控制台和视图。

The type-specific colored output really makes a difference if you need to visually scan for Stringor Numericobjects (Although I had to tweak my stylesheet a little bit in order to get a polished look)

如果您需要视觉扫描StringNumeric对象,特定于类型的彩色输出确实会有所不同(尽管我不得不稍微调整我的样式表以获得优美的外观)

回答by Dani?l W. Crompton

Recently I have become a fan of PRY, I've found it incredibly for doing things like inspecting variables, debugging running code and inspecting external code. It might be a little overkill as an answer to this specific question.

最近我成为了PRY的粉丝,我发现它非常适合做诸如检查变量、调试运行代码和检查外部代码之类的事情。作为对这个特定问题的回答可能有点矫枉过正。