Do you think IIT Guwahati certified course can help you in your career?
No
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
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.
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.
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.
--- !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]
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.
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.
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
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:
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.
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.