Current Date:July 13, 2024
Coding

How To Do Basic Caching Using Ruby on Rails

Today we are inaugurating a new section on our blog. In addition to the existing categories of our blog posts, we added the Coding section to share our knowledge with newcomers in the software development field. We will be posting in the future a few guides and tips on how to improve your skills as a software engineer/developer in different programming languages and frameworks.

For our first post, we asked Morgana Borges, an experienced Backend Developer of our team and a very skilled Ruby on Rails developer, to write a basic guide to talk to readers about a useful method to do caching in Rails.

What is Ruby on Rails

Ruby on Rails, often referred to as simply “Rails”, is a popular open-source web application framework that uses the Ruby programming language. Danish programmer, David Heinemeier Hansson, created this framework back in 2004. Since then, it became one of the most widely used web development frameworks. Rails provides a set of tools and conventions that help developers build complex web applications quickly and easily. It follows the Model-View-Controller (MVC) architecture pattern, which separates the application’s data, presentation, and logic into separate components. This makes it easier to maintain and modify the application over time.

Rails include many built-in features, such as an ORM (Object-Relational Mapping) system that simplifies database access, a routing system for handling HTTP requests, and a templating system for generating HTML pages. It also includes a vast library of plugins and extensions giving additional functionality to the framework. Overall, Ruby on Rails is a powerful and flexible web development framework, well-suited for building complex and scalable web applications.

What is caching

Caching is the process of storing data in a temporary storage area. That way you can quickly retrieve data the very next time you needed it. Caching is useful for computer systems to improve performance by reducing the time it takes to access data. In web development, the most common use for caching is to speed up the delivery of web pages to users.

When a user requests a web page, the server can cache the page’s content in memory or on disk. The next time the user requests the same page, the server can quickly retrieve the cached version instead of generating the page from scratch. This can significantly reduce the page’s load time and improve the user’s experience.

Also, you can use caching at various levels of the application stack, including the database level, the application level, and the network level. For example, a database might cache frequently accessed data in memory to reduce the time it takes to retrieve the data from a disk. An application might cache the results of a computationally expensive operation to avoid having to repeat the operation each time it is needed. And a network might cache frequently accessed web pages to reduce the bandwidth required to deliver the pages to users.

How to do caching with Ruby on Rails

In this section, we will discuss a few of the most common methods to do caching methods in the Ruby on Rails framework.

#1 – cache_if:

When a block of code is challenging to compute, you might want to cache the result of the command only when meeting a certain condition. This command is useful when you want to store the block of code under specific circumstances. For instance, suppose a user is not authenticated. In that case, you may not want to cache some elements of a webpage personalized to the user. But if the user is logged in, saving those parts in the cache can boost the application’s efficiency.

Example 1: caching a partial view only if the user is logged in.

 cache_if(current_user.present?, "user_sidebar") do %>
  <div class="sidebar">
    <!-- sidebar content for logged-in users here -->
  </div>
<% end %>

Example 2: caching the result of a database query only if a specific parameter is present in the request.

@products = if params[:category_id].present?
  cache_if(params[:category_id].present?, tag: "products_by_category_#{params[:category_id]}") do
    Product.where(category_id: params[:category_id]).all
  end
else
  Product.all
end

#2 – cache_unless:

Using this command you can indicate the condition that needs to be untrue to cache the block of code. For instance, if a user lacks admin privileges, it might not be suitable to cache specific sections of a webpage that only admins can access. However, if the user has admin rights, holding onto those parts in the cache can enhance the application’s speed.

Example 1: caching a frequently-accessed database query result only if the user is not a guest.

@products = if current_user.guest?
  Product.all
else
  cache_unless(current_user.admin?, tag: "products_by_user_#{current_user.id}") do
    current_user.products.all
  end
end

Example 2: caching the result of a remote API call only if the user is not an admin.

@weather = cache_unless(current_user.admin?, tag: "weather_for_#{params[:location]}") do
  WeatherAPI.get_weather(params[:location])
end

#3 – cached: true:

Rails’ render method can include an option that tells the system to cache the rendered template’s output. When activated, the system will reuse the cached data from previous renders rather than generating the same template from the start whenever a request is made. This approach accelerates the rendering process, reducing the time it takes to serve the output.

Example 1: caching a partial view with a dynamic key.

<%= render partial: "product", object: @product, cached: true, cache: "product/#{params[:id]}" %>

Example 2: caching an entire view for an hour.

<% cache("products_index", expires_in: 1.hour) do %>
  <% @products.each do |product| %>
    <%= render partial: "product", object: product, cached: true, cache: "product/#{product.id}" %>
  <% end %>
<% end %>

#4 – cache_store:

Ruby on Rails has a setting that lets you choose where to save cached information. You can select a file system cache, a memory cache, or an external caching tool like Redis or Memcached. This feature gives you the flexibility to choose the caching method that best suits your application’s needs.s.

Example 1: using the file system cache store.

# config/environments/production.rb
config.cache_store = :file_store, "tmp/cache"

Example 2: using Redis as the cache store.

# config/environments/production.rb
config.cache_store = :redis_cache_store, { url: ENV["REDIS_URL"], namespace: "cache" }

So what are your thoughts about the guide? Did you find it useful? Please, let us know in the comments below or contact us on our blog page or our website.

Leave a Reply

Your email address will not be published. Required fields are marked *