Useful tips when developing Ruby apps

Useful tips when developing Ruby apps


Hi everyone, bellow are some advises for developers developing Ruby / Rails apps for newbie.

Avoid too much logic in controllers
From my view, Ruby is mainly focus on MVC, and one common mistake that many people (including me) is coding logic at Controller layer.
Solution: Create Service layer to handle business logic, Controller mostly for receiving parameters from View, pass to Service layer, and write Logs.

Avoid complex logic in one function
There should be maximum 3 nested if-else, 2 nested loop for each function. If you cannot avoid that, split that function into smaller functions.
One helpful tool is Rubocop (Terminal: gem install rubocop) - details how to install / using

Read the article about ActiveRecord when dealing with Model relationship
Useful links:
In Ruby, the Model has some conventions on naming (for example, Model A has-one Model B, or A has-many B, will affect the way you define / calling).
Reading about :include, :preload... on ActiveRecord will improve coing performance and prevent n+1 issue

Be careful with gem
In Ruby, gems have dependencies, and some dependencies could be outdated or be incompatible when upgrade to new version. Remember to rebuild, cross check whenever you upgrade anything.

Use another language for View layer if you're developing website
You can use helpers in views whenever you feel the same code is repeated often, Use layouts and partials when the same code often repeats in views.
But for me, Rails is not very well support for View layer, so I suggest using another tech for FrontEnd together with Rails (Vue or React as FE, with Ruby/Rails as BE).

Thanks for reading :)