SlideShare a Scribd company logo
1 of 11
“Ruby on Rails Delegate :
Don’t break the Law of
Demeter ! ”
Copyright 2016. Jyaasa Technologies. All Right Reserved
http://jyaasa.com
I am Sarbada Nanda Jaiswal
Associate Software Engineer at
Jyaasa Technologies
Law of demeter
Each unit should have only limited knowledge about other
units: only units "closely" related to the current unit.
Each unit should only talk to its friends; don't talk to
strangers.
Only talk to your immediate friends.
In object-oriented programming
An object should not call methods through another object.
When using Rails and the cool association feature, it
can be tempting to chain methods calls like this:
● product.provider.name
● provider.address.city
● company.building.city
These lines violate the Law of Demeter. To fix it, we
should change them to be :
● product.provider_name
● provider.address_city #or provider.city
● company.city
This way, it’s much cleaner and we don’t break the law anymore. But
to do that, we need to add a bunch of methods to our models :
class Product < ActiveRecord::Base
belongs_to :provider
def provider_name
provider.name
end
# More methods to access the provider's attributes
end
class Provider < ActiveRecord::Base
has_many :products
# Has a name attribute
end
We define methods for each attribute like this. But Rails has
a solution : Delegate
class Product < ActiveRecord::Base
belongs_to :provider
delegate :name, to: :provider, prefix: true
end
class Provider < ActiveRecord::Base
has_many :products
# Has a name attribute
end
Options:
o :to - Specifies the target object
o :prefix - Prefixes the new method with the target name or a custom
prefix
o :allow_nil - if set to true, prevents a NoMethodError to be raised
Note the use of the prefix key. It allows us to use product.provider_name instead of just
product.name since a product would probably have its own name.
Delegate is a really powerful feature that let you clean up your models.
Let’s see another example.
If we have a Company that belongs to a Building, we could do :
class Company < ActiveRecord::Base
belongs_to :building
delegate :street, :city, :country, to: :building, allow_nil: true
end
class Building < ActiveRecord::Base
has_many :companies
attr_accessible :street, :city, :country
end
Thanks
Copyright 2016. Jyaasa Technologies. All Right Reserved
h
ttp://jyaasa.com

More Related Content

Similar to Rails Delegate: Avoid Breaking the Law of Demeter

Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJSTroy Miles
 
AngularJS Beginner Day One
AngularJS Beginner Day OneAngularJS Beginner Day One
AngularJS Beginner Day OneTroy Miles
 
Commonly used design patterns
Commonly used design patternsCommonly used design patterns
Commonly used design patternsMojammel Haque
 
2010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week12010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week1Wolfram Arnold
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with RailsPaul Gallagher
 
The Next Five Years of Rails
The Next Five Years of RailsThe Next Five Years of Rails
The Next Five Years of RailsAlex Mercer
 
Introduction to Drools
Introduction to DroolsIntroduction to Drools
Introduction to Droolsgiurca
 
Can't Dance The Lambda
Can't Dance The LambdaCan't Dance The Lambda
Can't Dance The LambdaTogakangaroo
 
WebNano - Ideas for Web Frameworks
WebNano - Ideas for Web FrameworksWebNano - Ideas for Web Frameworks
WebNano - Ideas for Web Frameworksguestf89f9cb
 
Intro to Ruby on Rails
Intro to Ruby on RailsIntro to Ruby on Rails
Intro to Ruby on RailsMark Menard
 
AGADOS function & feature Chapter-02 biz logic define
AGADOS function & feature Chapter-02 biz logic defineAGADOS function & feature Chapter-02 biz logic define
AGADOS function & feature Chapter-02 biz logic defineYongkyoo Park
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)Chiew Carol
 
Nhibernate Part 1
Nhibernate   Part 1Nhibernate   Part 1
Nhibernate Part 1guest075fec
 
Carlosbrando Rubyonrails21 En
Carlosbrando Rubyonrails21 EnCarlosbrando Rubyonrails21 En
Carlosbrando Rubyonrails21 EnCasey Bradford
 
Ruby on Rails 2.1 What's New
Ruby on Rails 2.1 What's NewRuby on Rails 2.1 What's New
Ruby on Rails 2.1 What's NewLibin Pan
 

Similar to Rails Delegate: Avoid Breaking the Law of Demeter (20)

Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
 
AngularJS Beginner Day One
AngularJS Beginner Day OneAngularJS Beginner Day One
AngularJS Beginner Day One
 
Commonly used design patterns
Commonly used design patternsCommonly used design patterns
Commonly used design patterns
 
2010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week12010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week1
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with Rails
 
The Next Five Years of Rails
The Next Five Years of RailsThe Next Five Years of Rails
The Next Five Years of Rails
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Good Coding Practices with JavaScript
Good Coding Practices with JavaScriptGood Coding Practices with JavaScript
Good Coding Practices with JavaScript
 
Ruby For Startups
Ruby For StartupsRuby For Startups
Ruby For Startups
 
Introduction to Drools
Introduction to DroolsIntroduction to Drools
Introduction to Drools
 
Can't Dance The Lambda
Can't Dance The LambdaCan't Dance The Lambda
Can't Dance The Lambda
 
WebNano - Ideas for Web Frameworks
WebNano - Ideas for Web FrameworksWebNano - Ideas for Web Frameworks
WebNano - Ideas for Web Frameworks
 
Intro to Ruby on Rails
Intro to Ruby on RailsIntro to Ruby on Rails
Intro to Ruby on Rails
 
AGADOS function & feature Chapter-02 biz logic define
AGADOS function & feature Chapter-02 biz logic defineAGADOS function & feature Chapter-02 biz logic define
AGADOS function & feature Chapter-02 biz logic define
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
Rspec
RspecRspec
Rspec
 
Nhibernate Part 1
Nhibernate   Part 1Nhibernate   Part 1
Nhibernate Part 1
 
Carlosbrando Rubyonrails21 En
Carlosbrando Rubyonrails21 EnCarlosbrando Rubyonrails21 En
Carlosbrando Rubyonrails21 En
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Ruby on Rails 2.1 What's New
Ruby on Rails 2.1 What's NewRuby on Rails 2.1 What's New
Ruby on Rails 2.1 What's New
 

More from Jyaasa Technologies (20)

Incident management with jira
Incident management with jiraIncident management with jira
Incident management with jira
 
Extreme programming practices ( xp )
Extreme programming practices ( xp ) Extreme programming practices ( xp )
Extreme programming practices ( xp )
 
The myth of 'real javascript developer'
The myth of 'real javascript developer'The myth of 'real javascript developer'
The myth of 'real javascript developer'
 
Microservices
MicroservicesMicroservices
Microservices
 
Facade pattern in rails
Facade pattern in railsFacade pattern in rails
Facade pattern in rails
 
Scrum ceromonies
Scrum ceromoniesScrum ceromonies
Scrum ceromonies
 
An introduction to bitcoin
An introduction to bitcoinAn introduction to bitcoin
An introduction to bitcoin
 
Tor network
Tor networkTor network
Tor network
 
Collective ownership in agile teams
Collective ownership in agile teamsCollective ownership in agile teams
Collective ownership in agile teams
 
Push notification
Push notificationPush notification
Push notification
 
The Design Thinking Process
The Design Thinking ProcessThe Design Thinking Process
The Design Thinking Process
 
User story
User storyUser story
User story
 
Design sprint
Design sprintDesign sprint
Design sprint
 
Data Flow Diagram
Data Flow DiagramData Flow Diagram
Data Flow Diagram
 
OKRs and Actions Overview
OKRs and Actions OverviewOKRs and Actions Overview
OKRs and Actions Overview
 
Vue.js
Vue.jsVue.js
Vue.js
 
Active record in rails 5
Active record in rails 5Active record in rails 5
Active record in rails 5
 
Design Patern::Adaptor pattern
Design Patern::Adaptor patternDesign Patern::Adaptor pattern
Design Patern::Adaptor pattern
 
Association in rails
Association in railsAssociation in rails
Association in rails
 
Web design layout pattern
Web design layout patternWeb design layout pattern
Web design layout pattern
 

Recently uploaded

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 

Recently uploaded (20)

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 

Rails Delegate: Avoid Breaking the Law of Demeter

  • 1. “Ruby on Rails Delegate : Don’t break the Law of Demeter ! ” Copyright 2016. Jyaasa Technologies. All Right Reserved http://jyaasa.com
  • 2. I am Sarbada Nanda Jaiswal Associate Software Engineer at Jyaasa Technologies
  • 3. Law of demeter Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. Each unit should only talk to its friends; don't talk to strangers. Only talk to your immediate friends.
  • 4. In object-oriented programming An object should not call methods through another object.
  • 5. When using Rails and the cool association feature, it can be tempting to chain methods calls like this: ● product.provider.name ● provider.address.city ● company.building.city
  • 6. These lines violate the Law of Demeter. To fix it, we should change them to be : ● product.provider_name ● provider.address_city #or provider.city ● company.city
  • 7. This way, it’s much cleaner and we don’t break the law anymore. But to do that, we need to add a bunch of methods to our models : class Product < ActiveRecord::Base belongs_to :provider def provider_name provider.name end # More methods to access the provider's attributes end class Provider < ActiveRecord::Base has_many :products # Has a name attribute end
  • 8. We define methods for each attribute like this. But Rails has a solution : Delegate class Product < ActiveRecord::Base belongs_to :provider delegate :name, to: :provider, prefix: true end class Provider < ActiveRecord::Base has_many :products # Has a name attribute end
  • 9. Options: o :to - Specifies the target object o :prefix - Prefixes the new method with the target name or a custom prefix o :allow_nil - if set to true, prevents a NoMethodError to be raised Note the use of the prefix key. It allows us to use product.provider_name instead of just product.name since a product would probably have its own name.
  • 10. Delegate is a really powerful feature that let you clean up your models. Let’s see another example. If we have a Company that belongs to a Building, we could do : class Company < ActiveRecord::Base belongs_to :building delegate :street, :city, :country, to: :building, allow_nil: true end class Building < ActiveRecord::Base has_many :companies attr_accessible :street, :city, :country end
  • 11. Thanks Copyright 2016. Jyaasa Technologies. All Right Reserved h ttp://jyaasa.com