CSC/ECE 517 Fall 2013/ch1 1w12 vn: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
Line 232: Line 232:
Add binding.pry where we want to invoke Pry in the code.
Add binding.pry where we want to invoke Pry in the code.


 
[[File:prysetup.jpg|frame|none|Invoke Pry in the code‎]]


* Run the script. This will display the pry session.
* Run the script. This will display the pry session.

Revision as of 21:10, 17 September 2013

Debugging in Ruby on Rails

Introduction

Rails is an open-source web application framework which makes use of Ruby programming language. With its huge library of gems and support for MVC architecture, it provides an easy and clean approach for creating pages, talking to web server and dealing with databases. Debugging is always an important part of any application development for which Rails provides a tremendously good support despite being an interpreted language as opposed to C or Java or any other compiled language.

Debugging Options

Rails provides a range of options to make debugging easier. Some of these options have been discussed in the sections below. <ref>http://guides.rubyonrails.org/debugging_rails_applications.html</ref>

Debug Helpers

One of the easiest ways to debugging is to simply output the value of different variables which provides us the first look into what could be going wrong. This could be done in all of models, views and controllers. Rails provides three methods-debug, to_yaml and inspect to achieve this task. These methods create human-readable data from any object.<ref> http://ruby-doc.org/core-2.0.0/Object.html </ref> The examples below show the output when these methods are used in a view.

Code Output
<%= @users.to_yaml %> --- - !ruby/object:User attributes: id: 2 name: Jimmy Page email: jimmy.page@gmail.com created_at: 2013-09-14 02:37:16.322638000 Z updated_at: 2013-09-16 20:38:04.250678000 Z
<%= @users.inspect %> #<ActiveRecord::Relation [#<User id: 2, name: "Jimmy Page", email: "jimmy.page@gmail.com", created_at: "2013-09-14 02:37:16", updated_at: "2013-09-16 20:38:04">]>
<%= debug @users %>
---
- !ruby/object:User
attributes:
id: 2
name: Jimmy Page
email: jimmy.page@gmail.com
created_at: 2013-09-14 02:37:16.322638000 Z
updated_at: 2013-09-16 20:38:04.250678000 Z

Logger

Logger<ref> http://www.ruby-doc.org/stdlib-1.9.3/libdoc/logger/rdoc/Logger.html</ref> class in Ruby helps us log information at runtime . Depending on what we choose to save in the log file, it can give us a variety of information such as what SQL queries were sent to databases, methods executed on the controller, attributes of the controller. The default logger for Rails is ActiveSupport::Logger which creates a file(eg. development.log for development environment) under log/ directory.<ref> http://www.ruby-doc.org/stdlib-1.9.3/libdoc/logger/rdoc/Logger.html</ref> There are six logging levels supported by Logger class.<ref>http://www.ruby-doc.org/stdlib-2.0.0/libdoc/logger/rdoc/Logger.html </ref><ref> http://railscasts.com/episodes/56-the-logger</ref>

Error Name Error Level Description
UNKNOWN 5 (highest) An unknown message that should always be logged.
FATAL 4 An error that cannot be handled and results in a program crash
ERROR 3 An error that cannot be handled
WARN 2 A warning
INFO 1 Information about system operation
DEBUG 0 (lowest) Information for developers

Examples

logger.info "Users information successfully displayed"
logger.debug "Users contains #{@users}"
logger.fatal "The program could crash"


The different logging levels <ref> http://www.ruby-doc.org/stdlib-1.8.7/libdoc/logger/rdoc/Logger.html </ref> determine the importance of the message and whether a message is logged or not depends on the current severity level set for an environment. Logger class logs all the messages for which severity level is same or above the current level set. The default logger level for development and production environment is debug and info respectively.<ref> http://rubylearning.com/satishtalim/ruby_logging.html </ref>

Purpose Command/Method/Procedure
Change default log level config.log_level = :info #in any environment initializer

Rails.logger.level = 0 #anywhere

Configure a new logger config.logger = Logger.new(...)

User can pass STDOUT/STDERR or name of a file to the initializer depending on where the log messages need to be sent. The Logger class provides options which age the logfile when it reaches a certain size or time (daily/weekly/monthly etc).

logger = Logger.new('development.log', 'daily')
Clear log messages rake log:clear
Display log file information on terminal window(UNIX) tail -f log/development.log
Put custom messages for debug in models/controllers/views logger.debug

logger.debug_variables

Put custom messages for debug in any other custom class RAILS_DEFAULT_LOGGER
Change format of logger messages Override method format_messages(level, time, progname, message)

Tagged Logging

Debugging a large application could become cumbersome if user decides to log every minor information. Sure removing some of the low level messages could reduce clutter but it is not always an effective solution. Luckily, ActiveSupport::TaggedLogging class provides a way to filter log messages on the basis of tags which could be anything from subdomains to request ids. User can simply grep into or search log file(s) using tags and look for relevant results quickly.<ref> http://api.rubyonrails.org/classes/ActiveSupport/TaggedLogging.html </ref>

logger = ActiveSupport::TaggedLogging.new(Logger.new('logfile.log'))     #creates a new logger
logger.tagged("USR") { logger.info "User info obtained" }                #Logs as "[USR] User info obtained"
logger.tagged("USR", "Jimmy") { logger.info "Jimmy logged in" }          #Logs "[USR] [Jimmy] Jimmy logged in"
logger.tagged("USR") do
  logger.tagged("Jimmy") { logger.info "Jimmy there" }
  logger.info "USR there"
end
# logged as "[USR] [Jimmy] Jimmy there\n[USR] USR there\n"

Debugger Gem

Debugger gem provides a command-line interface for debugging Rails applications step by step as opposed to just logging information which we have discussed so far. With the help of debugger gem, user can put breakpoints, go through code step-wise, inspect contents of variables. The section below provides basic steps to install and use debugger.<ref> https://github.com/cldwalker/debugger </ref>


  • Installation

Run the following command in the command window/terminal.

$ gem install debugger


  • Invoke debugger

User can invoke debugger from inside the code by calling debugger method.

Calling debugger method‎


  • Start Web Server

Start web server in a separate window using --debugger option

$rails server --debugger
Notice Debugger enabled message‎


  • Execute Code

Execute the code as usually and as soon as it comes across debugger method, the code execution will stop and wait for further instructions from the user. The arrow shows where in code has debugger currently stopped.

The window displays 10 lines of code around the line where debugger has stopped‎


  • Commands

Enter help on the command prompt to find all the available commands user can use at this point.

Commands available to user


For further information about a command, use the command

$ help <method>
Help command usage

Ruby-debug Gem

This is debugger for Ruby 1.8. It checks what is going on inside the code of a Ruby program while it executes. Apart from other ways, we can use rdebug to invoke Ruby program by a debugger.Ruby-debug has four main kinds of features for finding bug<ref> http://bashdb.sourceforge.net/ruby-debug.html</ref>:

  1. Depict anything that seems doubtful to affect your program after starting the script
  2. Specify stop on the script at certain conditions.
  3. After the script has stopped, examine the results.
  4. Modify your script to correct the bug.

Ruby-debug’s prompt is (rdb:n) where n is the thread number. Steps to be followed to use ruby-debug are mentioned below  :

  • Install debugger gem :
 gem install ruby-debug
  • Go to config file and add below command :
 require ‘ruby-debug’
  • Invoke the debugger, call ‘debugger’ method on file. Put a breakpoint using ‘debugger’ in a file , find the bug and start the server again.
 rails server --debugger
  • Now, a debugger prompt will be opened which will look like this:
  • Use ‘help’ for available commands. We can also get a list of directives with "help", or "help backtrace" for the usage of specific directive. 'list', to take a look at where the application stops. Some useful commands are mentioned below :
Command Explanation
Backtrace To check all the previous code. To move inside the trace, use frame_n_command
Thread To switch between threads, list the ongoing thread, its status, to stop a thread, resume and to switch its context.
List lists all the code
info breakpoints _n_ or info break _n list breakpoints

Some other useful commands are ‘exit’, ‘finish’,‘step’, ‘continue’, ‘next’, ‘print’.

You can use ‘var’ method to print the variables and ‘display’ to watch the variables. To stop displaying, we use ‘undisplay_variableNumber’.

Pry Gem

Pry is is a runtime developer console and an alternative to IRB(what?). It provides many features for debugging code easily such as syntax highlighting, code indentation, ability to check source code or documentation without interrupting the current session. There is an indenting problem with IRB, Pry solves this problem by resetting the terminal output as soon as a new line is entered.

  • Install Pry

Include the following in gemfile

gem 'pry', :group => :development
gem 'pry-rails', :group => :development

Run the bundle install command

bundle install
  • Change IRB console to Pry Console

For a development environment, add this at the end of development.rb(add the code to corresponding files in other environment).

silence_warnings do
 require 'pry'
 IRB = Pry
end
  • Start a Pry session

Add binding.pry where we want to invoke Pry in the code.

Invoke Pry in the code‎
  • Run the script. This will display the pry session.
ruby -r pry file.rb. 
  • We can check the binded data by command
ls     #we can just type the name also
  • To show the source code/documentation of a method
show-method      #or 
show –doc
  • To move out of a breakpoint
CTRL+D

Graphical Debugger

Rubymine, a commercial IDE by JetBrains, has a graphical debugger for ruby and rails code. It provides important and useful features such as smart breakpoints, dedicated view for watches and stack, expression evaluator, etc. Some of the key features related to debugging are presented below.

  • Options

Rubymine debugger provides a lot of other options for debugging.

Rubymine Run window‎


  • Breakpoint

One can put breakpoint by simply clicking on the start of the line in the window or pressing Ctrl+Shift+F8. Breakpoint feature highlights the corresponding line in the code.

Creating breakpoint which highlights the corresponding line in the code


  • Frames, Variables and Watches

Rubymine debugger shows a separate window for frames, variables and watches when the execution hits a breakpoint. User can look in the corresponding window for more information.

Rubymine IDE when code execution hits a breakpoint. Notice the different windows for frames, variables and watches‎


  • Evaluate code and expressions

Users can type in expression or code and evaluate it when the breakpoint is hit or on the fly.

Pop-up window to evaluate code on the fly
Pop-up window to evaluate expression at the time of execution

Analysis

As one can gather from the information provided in the previous sections, there are quite a few debugging options available to tackle bugs in Rails applications. Depending on the severity of bug encountered, one can simply choose to output object contents or debug stepwise. The choice also depends on whether the debugger is free or commercially available. Here is a brief analysis.

Debug Option Free/Commercial Comments
Debug Helpers Free Inspect the contents of an object
Logger Free Support for outputting the contents of an object
Tagged Logging Free Support for outputting the contents of object. Tagging feature quite useful for multi-user/large applications.
debugger gem Free Support for step-wise command-line debugging. Lots of advanced features available.
debug-ruby gem Free .....
pry gem Free ...
Rubymine Commercial Support for step-wise graphical debugging. Lots of advanced features available.

Additional Info

The information provided in the sections above are mostly effective for general debugging in Rails. There are more options available which provide other useful features for debugging purposes.

  1. better_errors [1]
  2. jazz_hands [2]
  3. debugger-rails [3]

For more specific cases such as memory leak debugging, other choices are also available.

References

<references />