Table of Contents
Working with Ruby On Rails (ROR) is actually like a cakewalk for many but it would remain even smoother if you follow these simple effective tips & tricks while developing your application. So, developers, Start taking your notes! This 10 Useful Tips & Tricks of Ruby On Rails are just an epic savage for you!
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') end end
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) } end class ShirtsController < ApplicationController def index @white_shirts = Shirt.color(‘white’) @red_shirts = Shirt.color(‘red’) end end
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 the 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 Rails
- 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 with external services are don’t have much to do with the core responsibility of an Active Record model. The main core functionality of Active Record is to find and perform CRUD operations in the 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 many logics anywhere in MVC. At this stage, You might stop & think like where else we can use all our logic? did he say no to logics anywhere in rails? Obviously not! you have the full freedom to use your logic but not advisable to use inside of MVC. Instead, you can use all the logic 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 logics 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 knows that in rails there is a default log file 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 the future, if your application is extended, modified, or upgraded to the 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 Html Templating Language for your Views
By default, Rails uses the ERB Templating system that lets 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 is very easy when compared to ERB. Slim is a 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
9. Some Useful Gems to organize your code and to increase your app performance
i) Bullet – Powerful gem which increases application performance, It identifies the 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 the 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. Alongside, Also explore the latest version Ruby 2.6.0 preview1 & its excellent features in my previous blog.
Like to read more about Ruby On Rails, Blockchain Technology, IOT or any recent technologies & upcoming trends then have an eye on our largest blog repository that could help you with more technical blogs.
For any queries reach us via info@agiratech.com