Table of contents
1.
Introduction
2.
Debugging
3.
View Helpers
3.1.
The Debug Method
3.2.
To_yaml
3.3.
Inspect
4.
Logger
5.
Web-console gem
5.1.
Console
5.2.
Inspecting Variables
5.3.
Settings
6.
Memory Leaks
7.
Plugins for Debugging
8.
Frequently Asked Questions
8.1.
What is Rails?
8.2.
What is RubyGems?
8.3.
What is the impact of using logs?
8.4.
What is a console?
9.
Conclusion
Last Updated: Mar 27, 2024
Hard

Debugging in Ruby on Rails

Author Manish Kumar
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hi Ninja🥷! Grab your coffee, and let's cover an exciting topic. Debugging is a skill as essential as writing robust code. Bugs may hit your code due to errors in your code or from third-party libraries. 

In this blog, you will learn Debugging in Ruby on Rails. You will go through different strategies and approaches to debugging ruby on rails applications. Let us begin our journey on ‘debugging in ruby on rails’ application.

Debugging In Ruby on Rails

Debugging

It is a process to identify and remove errors in your code base. It involves techniques such as adding breakpoints, using linters or using IDE to spot bugs early. It would be best if you took proper measures to debug your code when the bugs are identified. The final step in debugging is to test rigorously and ensure that the applied corrections work.

Debugging

View Helpers

To inspect the contents of variables we have different methods:

  • The Debug Method
  • To_yaml Method
  • Inspect Method
     

Let’s discuss each of them briefly.

The Debug Method

Rails have their own debug method. The debug method solves this problem when you are unsure if the issue is with the database or the server code. It shows any missing object data in the front end. It creates human-readable information about the viewport. For example, if the user name is not visible, you can use the debug@user method to view all users' data.
 

<%= debug @user %>
<h2>User name:</h2>
<%= @user.name %>

 

Output:

--- !ruby/object:User
concise_attributes:
- !ruby/object:ActiveModel::Attribute::FromDatabase
  name: name
  value_before_type_cast: ExampleUser1
- !ruby/object:ActiveModel::Attribute::FromDatabase
  name: email
  value_before_type_cast: ninja@email.com
- !ruby/object:ActiveModel::Attribute::FromDatabase
  name: type
  value_before_type_cast: standard_user

 

The debug@user method will let you know if the user's name is successfully pulled from the database or not. If there is no error fetching data from the database, the error is on the view code.

To_yaml

Calling the to_yaml converts any object to YAML. The converted object is passed into the simple_format helper method for further formatting.

<%= simple_format @article.to_yaml %>
<p>
  <b>Title:</b>
  <%= @article.title %>
</p>

 

Output:

--- !ruby/object Article
attributes:
updated_at: 2022-07-31 20:25:47
body: It is a good debugger.
title: Coding Ninjas - Debugging in Ruby on Rails
published: t
id: "1"
created_at:  2022-07-31 20:25:47
attributes_cache: {}
Title: Coding Ninjas - Debugging in Ruby on Rails

Inspect

The inspect method displays object values in arrays or hashes. It prints object values as strings.

<%= [1, 2, 3, 4, 5].inspect %>
<p>
  <b>Title:</b>
  <%= @article.title %>
</p>

 

Output:

[1, 2, 3, 4, 5]
Title: Coding Ninjas - Debugging in Ruby on Rails

Logger

Using logs to debug is another good option. Logs are generated in runtime and can identify potential pitfalls. Rails handle separate log files for each runtime environment. Logs provide a backtrace and highlight potential problem areas. 

Records are handy for complex issues that don't crash the application. Logs are also crucial when tools such as web consoles cannot be used in production.

Logging

Let us now go through various logging techniques to learn how debugging in ruby on rails works:
 

1. Logger: Rails uses ActiveSupport::Logger class to log information. Other loggers such as log4r can also be used.

Use config/application.rb or any other environment file for specifying an alternate logger.

For example:

config.logger = Logger.new(STDOUT)
config.logger = Log4r::Logger.new("Application Log")

 

2. Log levels: You can set the log level to decide which level of logs you want. It is a kind of cut-off to determine which logs to display. To know the current status, use the Rails.logger.level method. It is useful when you don't want your records to be flooded.

Code to change default log level:

config.log_level = :warn # In any development environment initializer
Rails.logger.level = 0 # at any time

 

Log Levels

 

3. Sending Messages: Use the logger (debug|info|warn|error|fatal|unknown) method to write additional logs manually. Always write sensible and meaningful logs only. For example:

logger.debug "Ninja attributes hash: #{@ninja.attributes.inspect}"
logger.info "Task in progress...."
logger.fatal "Application terminated!"

 

4. Verbose Query Logs: Use this method when a single function generates multiple database calls. Activate the log technique by ActiveRecord::Base.verbose_query_logs = true . Rerun the method to find out the error.

 

5. Tagged Logging: When deploying multi-user and multi-account applications, it is helpful to use tagged logging. TaggedLogging helps by stamping request ids, subdomains etc., for easy debugging.

logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
logger.tagged("Coding") { logger.info "Ninjas" }                            # Logs "[Coding] Ninjas"
logger.tagged("Coding", "Ninjas") { logger.info "User" }                   # Logs "[Coding] [Ninjas] User"
logger.tagged("Coding") { logger.tagged("Ninjas") { logger.info "User" } } # Logs "[Coding] [Ninjas] User"

 

6. Impact of Logs on Performance:  Logging impacts performance slightly. It is noticeably more when logging to disk. Using the debug method will have more penalties than the: fatal because a more significant number of strings are logged. Also, having too many calls to the Logger is costly.

Web-console gem

One of the popular options to debugging in ruby on rails applications is by using a web console. Web console allows for creating interactive ruby sessions in the web browser itself. It is excellent for live debugging. Since it's not directly visible on screen, it does not affect your development. 

It is activated when there is an error. The app crashes and shows the actual error on the interactive console. You can install the web console by adding it to your gemfile and then execute the bundle.

Code to install the web console

group: development do
  gem 'web-console'
end

It would help to restrict the web console from executing any random code to improve performance.

Console

You can invoke the console by calling the console method in any view or controller.

In a controller:

class PostsController < ApplicationController
  def new
    console
    @post = Post.new
  end
end

 

In a view:

<% console %>
<h2>Ninja</h2>

Inspecting Variables

To list all the instance variables available in your context, call the instance_variables method.For recording all the local variables, use the local_variables method.

Settings

  • config.web_console.allowed_ips: Authorised list of IP addresses and networks
  • config.web_console.whiny_requests: Log when console rendering is prevented


Please do not use these settings in production because it runs plain Ruby on a remote server.

Memory Leaks

A memory leak is a red flag in any codebase. Ruby can also lead to leaks either in the Ruby code or at the C level. This section will teach you how to find and fix such leaks.

1. Valgrind: It is an application for detecting memory leaks at the C level. Memory leaks are possible if multithreading is not managed correctly or in race conditions. For example, memory is allocated using malloc(), but it is not freed using the free() method. Data is available until the app is terminated. 

There are Valgrind tools to identify and manage such problems automatically. It also classifies issues in detail for manual debugging. 

To install Valgrind, use the following code:

mkdir ~/src
cd ~/src
wget' http://valgrind.org/downloads/valgrind-3.5.0.tar.bz2'
tar xjf valgrind-3.5.0.tar.bz2
./configure
make
sudo make install

 

2. Identify a memory leak: An actual memory leak will increase memory use forever. Most apps will increase memory use until they hit a "plateau". 

To diagnose this, you can run:

$ bundle exec derailed exec perf:mem_over_time

It will boot your app, hit it with requests, and output the memory to stdout.

Plugins for Debugging

Plugins are pre-written packages in Rails to ease your debugging journey. Here is a list most commonly used plugins:

  • Query Trace: Adds query origin trace to logs
  • Better Errors: Replaces standard error page with custom error page with source code and variable inspection
  • Exception Notifier: Sends email notifications when an error occurs in the Rails application
  • RailsPanel: It is a chrome extension to view DB, parameter list, rendered views etc
  • Pry: An IRB and runtime development console

Frequently Asked Questions

What is Rails?

Rails is a server-side web application framework written in Ruby language. It is an MVC framework and provides a structure for databases, web services, and web pages.

What is RubyGems?

It is a package manager for the Ruby programming language. It provides a standard format for distributing Ruby packages and maintains a server for distribution.

What is the impact of using logs?

Logs may lead to reduced performance. It becomes prominent when logs are saved to disk. Ruby has to handle extra work and read through complex strings to generate logs.

What is a console?

A console is a command line interface to execute various commands. While working with servers, the command line becomes handy, providing different functionality on a few key presses.

Conclusion

This post gave you a brief overview of Debugging in Ruby on Rails. You learned various debugging techniques and best practices. We hope you had a good time reading our blog on ‘Debugging in Ruby on Rails’.

Here are a few key websites that will aid in your exploration of Ruby on Rails.

 

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem DesignMachine learning, and many more! But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.

 

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blog on Debugging in Ruby on Rails  if you find it helpful and engaging!

Happy Learning!!

Thank you
Live masterclass