SlideShare a Scribd company logo
Rails Best Practices
By
Nitesh Varma
Developer
Allerin Tech Pvt Ltd
What is best practices?
• Best practices are using approaches that not
only delivers superior results but also
consider feasibility and ongoing development
of the approach.
Need?
• With the fast pace of today’s agile development
industries, we know how important it is to complete a
project on time.
• We also recognize the importance of other factors
such as flexibility, readability & most important
performance of the application.
• Even experienced developers some time do not
consider above points at the initial stage of application
launch, but later it start deteriorating the performance
when the data’s in the application grows exponentially
and enhancement needs to be done in existing
application.
• Below are the some best practices in Rails ,
which should have to be considered at the
time of development when using Rails
framework.
Use Eager Loading (Prevent N + 1
query)
• Most of the time new Rails developers do not
use eager loading of objects in Rails.
• Eager Loading is highly recommended at the
time of development in Rails.
• It mainly resolved the common issues like N +
1 queries.
• We can detect the N + 1 queries issues by
using gem ‘Bullet’ in development
environment.
Don’t Rescue Exception, Rescue
Standard Error
Explicitly rescuing Exception will also rescue code
errors such as SyntaxError, LoadError etc.
Consider below begin-rescue syntax
If we do not use Exception type qualifier, then
Ruby will catch only StandardError, which is
probably what we want from begin-rescue:
Use query attribute
We always check if ActiveRecord’s attributes exist or not by nil?,
blank? or present? ? Rails provides a cleaner way for this by
query attribute.
Suppose locked is boolean value of users table.
General:
The query attribute is almost the same as the present? method
call on attribute, or the opposite of blank? method call. Each
attribute of ActiveRecord’s model has a query method, so we
don’t need to use the present? or blank? for ActiveRecord’s
attributes.
Re-factored:
Caching with instance variable or Use
memoization
How can we avoid the duplicated db query and duplicated
calculation? We can use following methods.
We can also do this with memoize
Use batched finder for large data query
Suppose you have social network website containing millions
of user and you needs to send daily notification to them
morning.
Using find_each, the application only finds 1000 users once, yield them, then handle
the next 1000 users, until the last 1000 users. That means the application will only
load 1000 user objects into memory each time.
1000 is the default batch size, if we want to change batch_size we can use :batch_size
option to change it.
find_in_batches is similar to find_each except that it yields the array of objects
Replace instance variable with local variable
Partial is a reusable view template, In partial view, we can use
the instance variable directly, but it may be confused and make
it hard to reuse anywhere (variable leakage), because we don’t
know exactly which instance variable can be used, so we can
use the local variable in partial which will be explicitly
assignment at the time of render.
Questions?
Thank you

More Related Content

What's hot

Reflection in Pharo5
Reflection in Pharo5Reflection in Pharo5
Reflection in Pharo5
Marcus Denker
 
Akka framework
Akka frameworkAkka framework
Akka framework
mitesh_sharma
 
Akka - A Brief Intro
Akka - A Brief IntroAkka - A Brief Intro
Akka - A Brief Intro
Thomas Lockney
 
Metaprograming rails magic
Metaprograming rails magicMetaprograming rails magic
Metaprograming rails magic
Hieu Nguyen Trung
 
Javascript - Arrays - mutator functions
Javascript  - Arrays - mutator functionsJavascript  - Arrays - mutator functions
Javascript - Arrays - mutator functions
Samuel Santos
 
AngularJS best practices
AngularJS best practicesAngularJS best practices
AngularJS best practices
Filip Bruun Bech-Larsen
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
Patrick Sheridan
 
Introduction to the Actor Model
Introduction to the Actor ModelIntroduction to the Actor Model
Introduction to the Actor Model
BoldRadius Solutions
 
Introduction to Python Programming
Introduction to Python Programming Introduction to Python Programming
Introduction to Python Programming
Md. Shafiuzzaman Hira
 
Intro to javascript (5:2)
Intro to javascript (5:2)Intro to javascript (5:2)
Intro to javascript (5:2)
Thinkful
 
Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)
Brooklyn Zelenka
 

What's hot (15)

Reflection in Pharo5
Reflection in Pharo5Reflection in Pharo5
Reflection in Pharo5
 
Js tips & tricks
Js tips & tricksJs tips & tricks
Js tips & tricks
 
Lecture 13
Lecture 13Lecture 13
Lecture 13
 
Akka framework
Akka frameworkAkka framework
Akka framework
 
Akka - A Brief Intro
Akka - A Brief IntroAkka - A Brief Intro
Akka - A Brief Intro
 
Lecture 17
Lecture 17Lecture 17
Lecture 17
 
Metaprograming rails magic
Metaprograming rails magicMetaprograming rails magic
Metaprograming rails magic
 
Javascript - Arrays - mutator functions
Javascript  - Arrays - mutator functionsJavascript  - Arrays - mutator functions
Javascript - Arrays - mutator functions
 
AngularJS best practices
AngularJS best practicesAngularJS best practices
AngularJS best practices
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
 
Serialization
SerializationSerialization
Serialization
 
Introduction to the Actor Model
Introduction to the Actor ModelIntroduction to the Actor Model
Introduction to the Actor Model
 
Introduction to Python Programming
Introduction to Python Programming Introduction to Python Programming
Introduction to Python Programming
 
Intro to javascript (5:2)
Intro to javascript (5:2)Intro to javascript (5:2)
Intro to javascript (5:2)
 
Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)Relay: Seamless Syncing for React (VanJS)
Relay: Seamless Syncing for React (VanJS)
 

Viewers also liked

Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2
A.K.M. Ahsrafuzzaman
 
Clean Code
Clean CodeClean Code
Clean Code
Nascenia IT
 
Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17
Sławomir Zborowski
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
Alex Koppel
 
Creating an Adaptive Setting
Creating an Adaptive SettingCreating an Adaptive Setting
Creating an Adaptive Setting
David Keener
 

Viewers also liked (6)

Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2
 
Clean Code
Clean CodeClean Code
Clean Code
 
Presentation
PresentationPresentation
Presentation
 
Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Creating an Adaptive Setting
Creating an Adaptive SettingCreating an Adaptive Setting
Creating an Adaptive Setting
 

Similar to Rails best practices

How can JAVA Performance tuning speed up applications.pdf
How can JAVA Performance tuning speed up applications.pdfHow can JAVA Performance tuning speed up applications.pdf
How can JAVA Performance tuning speed up applications.pdf
Mindfire LLC
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
Katy Slemon
 
AliExpress’ Way to Microservices - microXchg 2017
AliExpress’ Way to Microservices  - microXchg 2017AliExpress’ Way to Microservices  - microXchg 2017
AliExpress’ Way to Microservices - microXchg 2017
juvenxu
 
Learning Web Development with Ruby on Rails Launch
Learning Web Development with Ruby on Rails LaunchLearning Web Development with Ruby on Rails Launch
Learning Web Development with Ruby on Rails Launch
Thiam Hock Ng
 
Building APIs using Laravel - A simple approach to scale
Building APIs using Laravel - A simple approach to scaleBuilding APIs using Laravel - A simple approach to scale
Building APIs using Laravel - A simple approach to scale
🤓 Steve McDougall
 
React Native App Development.
React Native App Development.React Native App Development.
React Native App Development.
Techugo
 
Rapid Application Development with MEAN Stack
Rapid Application Development with MEAN StackRapid Application Development with MEAN Stack
Rapid Application Development with MEAN Stack
Avinash Kaza
 
Comprehensive Guide to React Development 2022.pptx
Comprehensive Guide to React Development 2022.pptxComprehensive Guide to React Development 2022.pptx
Comprehensive Guide to React Development 2022.pptx
75waytechnologies
 
5 Key Metrics to Release Better Software Faster
5 Key Metrics to Release Better Software Faster5 Key Metrics to Release Better Software Faster
5 Key Metrics to Release Better Software Faster
Dynatrace
 
Managing Large Flask Applications On Google App Engine (GAE)
Managing Large Flask Applications On Google App Engine (GAE)Managing Large Flask Applications On Google App Engine (GAE)
Managing Large Flask Applications On Google App Engine (GAE)
Emmanuel Olowosulu
 
How to implement ruby on rails testing practices to build a successful web ap...
How to implement ruby on rails testing practices to build a successful web ap...How to implement ruby on rails testing practices to build a successful web ap...
How to implement ruby on rails testing practices to build a successful web ap...
Katy Slemon
 
All about that reactive ui
All about that reactive uiAll about that reactive ui
All about that reactive ui
Paul van Zyl
 
Beyond rails new
Beyond rails newBeyond rails new
Beyond rails new
Paul Oguda
 
A Beard, An App, A Blender
A Beard, An App, A BlenderA Beard, An App, A Blender
A Beard, An App, A Blender
edm00se
 
System design for Web Application
System design for Web ApplicationSystem design for Web Application
System design for Web Application
Michael Choi
 
Satish resume
Satish resumeSatish resume
Satish resume
Sateesh Allu
 
Top 3 Mistakes when Building
Top 3 Mistakes when BuildingTop 3 Mistakes when Building
Top 3 Mistakes when BuildingTalbott Crowell
 
Using MLOps to Bring ML to Production/The Promise of MLOps
Using MLOps to Bring ML to Production/The Promise of MLOpsUsing MLOps to Bring ML to Production/The Promise of MLOps
Using MLOps to Bring ML to Production/The Promise of MLOps
Weaveworks
 
Orchestration, the conductor's score
Orchestration, the conductor's scoreOrchestration, the conductor's score
Orchestration, the conductor's score
Salesforce Engineering
 
Building multi billion ( dollars, users, documents ) search engines on open ...
Building multi billion ( dollars, users, documents ) search engines  on open ...Building multi billion ( dollars, users, documents ) search engines  on open ...
Building multi billion ( dollars, users, documents ) search engines on open ...
Andrei Lopatenko
 

Similar to Rails best practices (20)

How can JAVA Performance tuning speed up applications.pdf
How can JAVA Performance tuning speed up applications.pdfHow can JAVA Performance tuning speed up applications.pdf
How can JAVA Performance tuning speed up applications.pdf
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
 
AliExpress’ Way to Microservices - microXchg 2017
AliExpress’ Way to Microservices  - microXchg 2017AliExpress’ Way to Microservices  - microXchg 2017
AliExpress’ Way to Microservices - microXchg 2017
 
Learning Web Development with Ruby on Rails Launch
Learning Web Development with Ruby on Rails LaunchLearning Web Development with Ruby on Rails Launch
Learning Web Development with Ruby on Rails Launch
 
Building APIs using Laravel - A simple approach to scale
Building APIs using Laravel - A simple approach to scaleBuilding APIs using Laravel - A simple approach to scale
Building APIs using Laravel - A simple approach to scale
 
React Native App Development.
React Native App Development.React Native App Development.
React Native App Development.
 
Rapid Application Development with MEAN Stack
Rapid Application Development with MEAN StackRapid Application Development with MEAN Stack
Rapid Application Development with MEAN Stack
 
Comprehensive Guide to React Development 2022.pptx
Comprehensive Guide to React Development 2022.pptxComprehensive Guide to React Development 2022.pptx
Comprehensive Guide to React Development 2022.pptx
 
5 Key Metrics to Release Better Software Faster
5 Key Metrics to Release Better Software Faster5 Key Metrics to Release Better Software Faster
5 Key Metrics to Release Better Software Faster
 
Managing Large Flask Applications On Google App Engine (GAE)
Managing Large Flask Applications On Google App Engine (GAE)Managing Large Flask Applications On Google App Engine (GAE)
Managing Large Flask Applications On Google App Engine (GAE)
 
How to implement ruby on rails testing practices to build a successful web ap...
How to implement ruby on rails testing practices to build a successful web ap...How to implement ruby on rails testing practices to build a successful web ap...
How to implement ruby on rails testing practices to build a successful web ap...
 
All about that reactive ui
All about that reactive uiAll about that reactive ui
All about that reactive ui
 
Beyond rails new
Beyond rails newBeyond rails new
Beyond rails new
 
A Beard, An App, A Blender
A Beard, An App, A BlenderA Beard, An App, A Blender
A Beard, An App, A Blender
 
System design for Web Application
System design for Web ApplicationSystem design for Web Application
System design for Web Application
 
Satish resume
Satish resumeSatish resume
Satish resume
 
Top 3 Mistakes when Building
Top 3 Mistakes when BuildingTop 3 Mistakes when Building
Top 3 Mistakes when Building
 
Using MLOps to Bring ML to Production/The Promise of MLOps
Using MLOps to Bring ML to Production/The Promise of MLOpsUsing MLOps to Bring ML to Production/The Promise of MLOps
Using MLOps to Bring ML to Production/The Promise of MLOps
 
Orchestration, the conductor's score
Orchestration, the conductor's scoreOrchestration, the conductor's score
Orchestration, the conductor's score
 
Building multi billion ( dollars, users, documents ) search engines on open ...
Building multi billion ( dollars, users, documents ) search engines  on open ...Building multi billion ( dollars, users, documents ) search engines  on open ...
Building multi billion ( dollars, users, documents ) search engines on open ...
 

More from Achintya Kumar

Clean code
Clean code Clean code
Clean code
Achintya Kumar
 
Speeding up web_application
Speeding up web_applicationSpeeding up web_application
Speeding up web_application
Achintya Kumar
 
Introduction to-angular js
Introduction to-angular jsIntroduction to-angular js
Introduction to-angular js
Achintya Kumar
 
Application lifecycle management
Application lifecycle managementApplication lifecycle management
Application lifecycle management
Achintya Kumar
 
Code Refactoring using rails
Code Refactoring using railsCode Refactoring using rails
Code Refactoring using rails
Achintya Kumar
 
Graph database
Graph databaseGraph database
Graph database
Achintya Kumar
 

More from Achintya Kumar (6)

Clean code
Clean code Clean code
Clean code
 
Speeding up web_application
Speeding up web_applicationSpeeding up web_application
Speeding up web_application
 
Introduction to-angular js
Introduction to-angular jsIntroduction to-angular js
Introduction to-angular js
 
Application lifecycle management
Application lifecycle managementApplication lifecycle management
Application lifecycle management
 
Code Refactoring using rails
Code Refactoring using railsCode Refactoring using rails
Code Refactoring using rails
 
Graph database
Graph databaseGraph database
Graph database
 

Recently uploaded

From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 

Recently uploaded (20)

From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 

Rails best practices

  • 1. Rails Best Practices By Nitesh Varma Developer Allerin Tech Pvt Ltd
  • 2. What is best practices? • Best practices are using approaches that not only delivers superior results but also consider feasibility and ongoing development of the approach.
  • 3. Need? • With the fast pace of today’s agile development industries, we know how important it is to complete a project on time. • We also recognize the importance of other factors such as flexibility, readability & most important performance of the application. • Even experienced developers some time do not consider above points at the initial stage of application launch, but later it start deteriorating the performance when the data’s in the application grows exponentially and enhancement needs to be done in existing application.
  • 4. • Below are the some best practices in Rails , which should have to be considered at the time of development when using Rails framework.
  • 5. Use Eager Loading (Prevent N + 1 query) • Most of the time new Rails developers do not use eager loading of objects in Rails. • Eager Loading is highly recommended at the time of development in Rails. • It mainly resolved the common issues like N + 1 queries. • We can detect the N + 1 queries issues by using gem ‘Bullet’ in development environment.
  • 6.
  • 7.
  • 8. Don’t Rescue Exception, Rescue Standard Error Explicitly rescuing Exception will also rescue code errors such as SyntaxError, LoadError etc. Consider below begin-rescue syntax
  • 9. If we do not use Exception type qualifier, then Ruby will catch only StandardError, which is probably what we want from begin-rescue:
  • 10. Use query attribute We always check if ActiveRecord’s attributes exist or not by nil?, blank? or present? ? Rails provides a cleaner way for this by query attribute. Suppose locked is boolean value of users table. General:
  • 11. The query attribute is almost the same as the present? method call on attribute, or the opposite of blank? method call. Each attribute of ActiveRecord’s model has a query method, so we don’t need to use the present? or blank? for ActiveRecord’s attributes. Re-factored:
  • 12. Caching with instance variable or Use memoization
  • 13. How can we avoid the duplicated db query and duplicated calculation? We can use following methods.
  • 14. We can also do this with memoize
  • 15. Use batched finder for large data query Suppose you have social network website containing millions of user and you needs to send daily notification to them morning.
  • 16. Using find_each, the application only finds 1000 users once, yield them, then handle the next 1000 users, until the last 1000 users. That means the application will only load 1000 user objects into memory each time. 1000 is the default batch size, if we want to change batch_size we can use :batch_size option to change it.
  • 17. find_in_batches is similar to find_each except that it yields the array of objects
  • 18. Replace instance variable with local variable Partial is a reusable view template, In partial view, we can use the instance variable directly, but it may be confused and make it hard to reuse anywhere (variable leakage), because we don’t know exactly which instance variable can be used, so we can use the local variable in partial which will be explicitly assignment at the time of render.
  • 19.