我正在寻找一种类似于 PHP 函数 print_r
和 var_dump
用于调试的方法,可以将一个对象的结构进行转储。
我正在寻找一种类似于 PHP 函数 print_r
和 var_dump
用于调试的方法,可以将一个对象的结构进行转储。
.inspect
方法可以正确格式化任何对象的显示,只需执行即可。
<%= theobject.inspect %>
.methods
方法可能也会有用:
<%= theobject.methods.inspect %>
视数据情况而定,将其放入<pre>
标签中可能会有所帮助。
<%= debug(yourobject) %>
,它将生成您的数据的 YAML 视图。如果您想在日志中查看某些内容,您应该使用logger.debug yourobject.inspect
。>> 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
>>
>> raise Rails.root
RuntimeError: /home/marcin/work/github/project1
from (irb):17
>>
我也非常鼓励你尝试使用ruby-debug:
它非常有帮助!
之前的答案很好,但如果您不想使用控制台(终端),在Rails中您可以通过使用debug的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
网页中的结果
- !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
p some_object
。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
ap
方法,它可以在控制台和视图中使用。String
或 Numeric
对象,类型特定的彩色输出确实会有所不同(尽管我不得不微调我的样式表以获得精美的外观)。
puts theobject.inspect.gsub(",", "\n")
。 - Gus