5 Best Practices for Ruby/Rails Beginners in 2023

Supradipta
by Supradipta 

Ruby is a dynamic, high-level, general-purpose programming language known for its simplicity and productivity. Ruby is the programming language behind several web applications, including GitHub, Airbnb, and Twitch.

Ruby on Rails (often called “Rails”) is a web application framework built using Ruby programming language. Rails is an efficient way to build web applications because it’s conventions and built-in tools that make it easy to get started. According to the BuiltWith Trends report, over 1.5 million websites are currently using Ruby on Rails as their web framework as of March 2023.

Overall, Ruby on Rails continues to be a popular choice for web development, particularly for startups and small to medium-sized businesses. Its focus on developer productivity, convention over configuration, and its extensive library of third-party gems make it a powerful and efficient framework for building web applications.

Why follow best practices?

As a software developer you do not just write and run code, you have to consider other factors such as reliability, maintainability, and security too. You also have to properly document everything, so that your fellow developers and team mates easily understand what is going on in the code.

To ensure the efficiency, consistency, maintainability, and scalability of our code, we follow certain best practices that are established by experienced programmers based on their years of experience and trial-and-error. Adhering to these practices will save you from common mistakes and pitfalls, reduce bugs and improve the quality of your code.

Best Practices in Ruby/Rails

At Gurzu, we have years of experience of working in Ruby and Rails. We have completed numerous projects and learnt many tips and tricks that will be helpful to beginners.

So, if you are new to Ruby/Rails, and are interested in honing your coding skills, you have landed the right place! Here are 5 of the hand-picked best practices that you must follow if you are a beginner in Ruby/Rails.

1. Use ‘each’ instead of ‘for’

  • each is generally faster and more idiomatic. [can be benchmarked with benchmark library in Ruby.]

gurzu ruby best practices for in

gurzu ruby best practices each

  • last variable value could be accessed outside of the scope in case of for…in and is not accessible in case of each.

Ruby good practice Gurzu

Ruby bad practice

#Bad Practice
for elem in [1, 2, 3, 4, 5]
  puts elem
end
#Good Practice
[1, 2, 3, 4, 5].each { |elem| puts elem }

2. Use ‘Case/when’ conditions instead of lengthy “if” statements

With “if” statements, developers often end up writing lengthy and repetitive code blocks that can be difficult to follow. In contrast, “case/when” conditions allow developers to group related conditions together, making the code easier to read and maintain.

Another advantage of “case/when” conditions is that they can provide better performance when dealing with large numbers of conditions. Since “if” statements are evaluated sequentially, each condition must be checked in turn. In contrast, “case/when” conditions can be optimized by the Ruby interpreter, allowing for faster execution.

puts "What is your task status?"
status= gets.chompcase status
when ‘inprogress’
  puts "The task is in progress. Rapidly working on it."
when ‘hold’
  puts "The task is in hold. Will work on it after client's feedback."
when ‘done’
  puts "The task has been completed. Got a good response from the client."
else
  puts "The task is in TODO."
end

3. Use double bangs(!!) to determine if the value exists

The double bangs are a shorthand way of converting any value to a Boolean. The first bang (!) negates the value, and the second bang converts the negation back to its original Boolean value.

@middle_name #=> nil
!@middle_name #=> true
!!@middle_name #=> false

4. Avoid N+1 query

Rails has a (in)famous query problem known as the N+1 query problem. Take the following case where a user has a house:

class User < ActiveRecord::Base
  has_one :house
end


class House < ActiveRecord::Base
  belongs_to :user
end
#Bad Practice
@users = User.limit(50)

<% @users.each do |user|%>
  <%= user.house.address %>
<% end %>

The above code will execute 51 queries, 1 to fetch all users and other 50 to fetch the house of each user.

#Good Practice
@users = User.includes(:house).limit(50)

<% @users.each do |user|%>
  <%= user.house.address %>
<% end %>

The above code will execute 2 queries, 1 to fetch all users and other to fetch houses for the user.

Check this: Bullet – A gem that warns of N+1 select (and other) issues

5. Follow the Law of Demeter

According to the law of Demeter, a model should only talk to its immediate associated models. If you want to use associated attributes then you should use ‘delegate’. Using this paradigm, a model delegates its responsibility to the associated object. Read more about law of demeter here.

# Bad Practice
class Project < ActiveRecord::Base
  belongs_to :creator
end

<%= @project.creator.name %>
<%= @project.creator.company %>
# Good Practice
class Project > ActiveRecord::Base
  belongs_to :creator
  delegate :name, :company, :to => :creator, :prefix => true
end

<%= @project.creator_name %>
<%= @project.creator_company %>

Final Words

And there you have it - the essential Ruby/Rails best practices to help you build amazing web applications like a pro! So go forth, code with confidence, and take your Ruby/Rails skills to the next level. Happy coding!

.………….

Gurzu is a diverse team of creatives, technologists, data scientists, security experts, and entrepreneurs helping world-class customers get to their markets quickly with high quality products built with modern software technologies.

Need a team of expert Ruby developers for your project? Get in touch with us or book a free consulting call!