I'm looking for a way to dump the structure of an object, similar to the PHP functions print_r
and var_dump
for debugging reasons.
views:
1030answers:
6In views:
DebugHelper’s debug(object)
In controllers, models, and other code:
puts YAML::dump(object)
The .inspect
method of any object should format is correctly for display, just do..
<%= theobject.inspect %>
The .methods
method may also be of use:
<%= theobject.methods.inspect %>
It may help to put that in <pre>
tags, depending on the data
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
.
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
.
You can also use YAML::dump shorthand (y) under Rails console:
>> 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 Rails.root
RuntimeError: /home/marcin/work/github/project1
from (irb):17
>>
I also really encourage you to try ruby-debug:
- http://railscasts.com/episodes/54-debugging-with-ruby-debug
- http://www.sitepoint.com/article/debug-rails-app-ruby-debug/
- http://www.datanoise.com/articles/2006/7/12/tutorial-on-ruby-debug
It's incredibly helpful!
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