Search code examples
ruby-on-railsrubydebugging

How to debug using rails console and puts in application


I want to get some lines printed in irb opened through rails console. I have seen a lot of SO questions of how to achieve it. But I get nothing in the irb.

below is the code--

def show
puts 'in show method'
@post = Feed.find_by_id params[:id]
puts @post.inspect
redirect_to root_path unless @post.present? 
end

now I have opened server by command rails server. Also, In another terminal I gave the command rails console, it opened the irb prompt. when in browser I run localhost:3000/posts/82 it gives the correct post, but nothing is shown in the console. What step am I missing? I want to print something in the console when a particular method is called.


Solution

  • Best way to debug is to use the debugger command.

    If you are using ruby 2.0 or above, you have to use the gem 'byebug' and if you are using 1.9 or below, then gem ruby-debug

    then, when you run your server in development mode, your server will stop when it reaches the debugger allowing you to see your objects' state and modify them (much better than simply using puts

    The program will stop in the same window that your server runs.

    Some basic commands:

    • c continues the execution until next debugger is found
    • n runs the next command. If it is a function executes the function
    • s step into the next command. If it is a function, you will get into the function and see the variables
    • display expression on every step display the result of the expression you write (very useful when debugging loops)
    • undisplay expression_number stops displaying the expresion
    • display shows all the expressions being displayed
    • list Displays the source code being executed
    • help shows the available commands help command_name shows detailed info about a command

    More info about debugging: http://guides.rubyonrails.org/debugging_rails_applications.html