Ruby on Rails Best Coding Practices

Wajeeh Ahsan
6 min readJan 27, 2020

--

Table of Content
1- Don’t Put Too Much Logic In The Controller
2- Don’t put too much logic in the view
3- Don’t put too much logic in the Model
4- Don’t Use Too Many Gems
5- Always Check Your Logs
6- Always Write Automated Tests
7- Background Tasks
8- Use Slim or Haml Templating Language for your Views
9- Some Useful Gems to organize your code and to increase your app performance
10- Some Useful Ruby On Rails Tips

1- Don’t Put Too Much Logic In The Controller

Rails is based on MVC architecture. Maintain a skinny controller is one of the most important things to increase the readability and testability of the code.
For example, you have a controller wherein the index method will extract the list of red and white color shirts.

class ShirtsController < ApplicationController def index  @white_shirts = Shirt.where(color: ‘White’)  @red_shirts = Shirt.where(colour: ‘Red’) endend

To define these queries even more specific, Now, Migrating this code to the database entitled “Shirt model” to extract the red and white, Hope you can see how easier to write index method of the controller.

class Shirt < ActiveRecord::Base  scope :color, -> (option){ where(color: option) }endclass ShirtsController < ApplicationController  def index    @white_shirts = Shirt.color(‘white’)    @red_shirts = Shirt.color(‘red’)  endend

Always follow the second approach when you’re facing Database Queries in the controller method

We do have many logics, but these are the best practices we can use in the controller.

  • Logic for Session and Cookie handling
  • Logic for finding correct model to perform DB operations
  • Logic for Rendering the result based on request type like HTML, XML, JSON, etc. or redirecting
  • Logic for Collecting the parameters and using that to perform operations based on your requirement.

2- Don’t put too much logic in the view

ERB is a great way to build your views by embedding ruby inside HTML. However you need to be very careful while building your views, big view files are difficult to manage and maintain. This is also an area where is a possibility of getting of facing code repetition and sometimes that leads to violations like DRY(don’t repeat yourself principles).

A couple of recommended best practices of

  • Always try to use helpers in the views
  • Use layouts and partials when you feel the same type of code repeating multiple times in the views
  • Use presenters/decorators like the Draper gem, this will greatly help you to reduce the code in your view files.

3- Don’t put too much logic in the Model

Some functionality like generating email notifications, interfacing to external services are don’t have much to do with core responsibility of an Active Record model. The main core functionality of Active Record is to find and perform CRUD operations in database.

And some of the best logic’s we can use in Model is,

  • Active Record relations(Associations) and validations
  • Simple methods which will update attributes and save them in a database.
  • Access Wrappers to hide internal model information(for example full_name method that combines the first_name and last_name fields in the database)
  • Database related queries — Always try to avoid using any Active Record queries outside of the model.

Literally, I have been mentioning like don’t use too much logic’s anywhere in MVC. At this stage, You might stop & think like where else we can use all our logic’s? did he saying no to logic’s anywhere in rails? Obviously not! you have the full freedom to use your logic’s but not advisable to use inside of MVC. Instead, you can use all the logic in outside of the MVC which will not disturb the performance of the application at the same time it’s easy for us to manage the logic too.

4- Don’t Use Too Many Gems

Always keep in mind that each gem you add in your application may have dependencies on other gems and that gems may have dependencies on some other gems so on.

Using more number of gems makes the size of your Rails application larger than it needs to be. This may slow down the application performance in Production. This also may lead to larger server memory configurations and increased operating costs.

Do you know that adding the gem ‘rails_admin’ will add 11 more gems to your application? That 11 more gems may have some more dependent gems and so on.

So always be careful and crosscheck while adding gems to your application.

5- Always Check Your Logs

As all Ruby on Rails developers already know that in rails there is a default log files available in development and in production, most of the developers will ignore the information in these files, it is important to look at your log files throughout the development and testing your application so you can keep track the process flow.

For example, you will often run into is N+1 query problem and the only way to identify this N+1 query problem is by reviewing your log files.

Reviewing log files is a great way to find inefficiencies in your code.

6- Always Write Automated Tests

There should be at least one high-level test case written for each action in your controller. At some point in future, if your application is extended, modified or upgraded to a latest ROR version, this testing framework will give a clear way of verifying the basic functionality of your application. You may also find some defects in your logic by writing test cases.

7- Background Tasks

We used to integrate third-party services into our applications via gems which calls their API’s, but we cannot ensure that it will always run normally, what if the service starts running very slowly?

To avoid this blocking of calls, you can make them as background tasks, instead of directly calling these services as a normal request in your rails application.

Here are some popular gems used for this purpose,

  • Delayed Job
  • Sidekiq
  • Resque

8- Use Slim or Haml Templating Language for your Views

By default, Rails uses the ERB Templating system that let you embed Ruby code inside HTML, If possible always try to use Slim or HAML template systems which are more lightweight than ERB. Additionally, This Slim or HAML syntax are very easy when compared to ERB. Slim is very fast, lightweight templating engine. By using this you can achieve code cleanliness, more readability, and it may also reduce the response time of your request. Also, this also helps to build your front-end very fast.

9- Some Useful Gems to organize your code and to increase your app performance

i) Bullet — Powerful gem which increases application performance, It identifies N+1 query problem and shows an alert message on your browser
ii) Traceroute — It identifies unused routes in your application.
iii) Rails Best Practices — It checks code quality of rails application and provides suggestions.
iv) Dead-weight — It identifies unused CSS selectors.

10- Some Useful Ruby On Rails Tips

i- Indexing: Database indexing is one of the simplest ways to improve database performance. It will boost up fetching data from the database.
ii- Views: Never call the DB related queries from your views, it will significantly impact on your app performance
iii- Controller variables: All the dynamic data which you are using in the views must be defined by the controller variables.
iv- SAAS: Always write your styles(CSS) in SAAS approach, this will always prevent you from style overrides.
v- content tag: Avoid content_tag in helpers, rather calling them in partials.
vi- helpers: Rails generate by default one helper per controller. Remove them all and use aspect-oriented helpers like form helper, links helper, menu helper, image helper, etc

Apart from all, it’s always good to know the recent updates and latest versions. If any new version of Ruby or Rails is released, try to explore and experiment with the new features of that version. That would always help you to Master the development arena.

--

--

Wajeeh Ahsan
Wajeeh Ahsan

No responses yet