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.
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
>>
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
Lately I'm using awesome_print's ap method which works on the console as well as in views.
The type-specific colored output really makes a difference if you need to visually scan for String or Numeric objects (Although I had to tweak my stylesheet a little bit in order to get a polished look)
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.
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
#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