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

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


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.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

In views:

include DebugHelper

...your code...

debug(object)

In controllers, models, and other code:

puts YAML::dump(object)

Source

Solution 3 - Ruby on-Rails

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.

Solution 4 - Ruby on-Rails

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:

It's incredibly helpful!

Solution 5 - Ruby on-Rails

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.

Solution 6 - Ruby on-Rails

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.

Solution 7 - Ruby on-Rails

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

Solution 8 - Ruby on-Rails

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

Solution 9 - Ruby on-Rails

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)

Solution 10 - Ruby on-Rails

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel RikowskiView Question on Stackoverflow
Solution 1 - Ruby on-RailsdbrView Answer on Stackoverflow
Solution 2 - Ruby on-RailsArtem RussakovskiiView Answer on Stackoverflow
Solution 3 - Ruby on-RailsujhView Answer on Stackoverflow
Solution 4 - Ruby on-RailsMarcin UrbanskiView Answer on Stackoverflow
Solution 5 - Ruby on-RailsTrantor LiuView Answer on Stackoverflow
Solution 6 - Ruby on-RailsMikoangeloView Answer on Stackoverflow
Solution 7 - Ruby on-RailsPapouche GuinslyzinhoView Answer on Stackoverflow
Solution 8 - Ruby on-RailsPawel BarcikView Answer on Stackoverflow
Solution 9 - Ruby on-RailsDaniel RikowskiView Answer on Stackoverflow
Solution 10 - Ruby on-RailsDaniël W. CromptonView Answer on Stackoverflow