SlideShare ist ein Scribd-Unternehmen logo
1 von 52
Downloaden Sie, um offline zu lesen
R A I L S O N M A U I
1
Concerns, Decorators, Presenters, Service
Objects, Helpers, Help me Decide!
RailsConf 2014
Chicago
April 22, 2014
!
Justin Gordon
@railsonmaui
Rails Consultant
www.railsonmaui.com
2
3
Controller
Model &
Avoid the
Ball of Mud
May seem fun…	

!
Guaranteed:	

the perpetrator is	

not doing the cleanup!	

4
• Show Redmine,
• AccountsController, lost_password action
• UserModel, big class, 762 Lines
5
Sandi Rules
method > 5 lines
class > 100 lines
😱
6
How do we organize the mess?
Organizational Conventions Matter
7
Department Store
What if the clothing store was organized by color?
What if a clothing store was organized by size?
Organizational Conventions Matter
8
Thrift Store
What if no organization?
Like Fashion…
Coding Style ➜ Personal Preference
9
• Coding is like writing!
• Tons of disagreement in the Rails community over names, patterns, etc.
• But let’s agree on a few things..
And Our Style is…
10
Prefer the Rails default framework (Models, Model Concerns, Controllers, Controller Concerns)
Know Rails really well! Assume team members also know rails!
DHH Quote
JG: "This is starting to boil down to utilize the framework
capabilities and move beyond only when necessary.”	

DHH: "Which is really just an extension of KISS (Keep It
Simple, Stupid). When you use the
framework code for what it’s
intended, you’re not cutting
against the grain. You don’t need to write as
much code. It’s clearer to everyone because it’s the same
approach everyone else is taking."
11
Microposts Example
12
Micropost Model
User Model
Micropost Controller
User Controller
1
N
Refactoring Examples in Pull Requests
• https://github.com/justin808/fat-code-refactoring-techniques/
pulls	

• Based on Michael Hartl’s “Rails Tutorial” MicroBlog example
application
13
• Github PRs are the most AMAZING place to discuss code!
• Clean up the Microblog code a little, demonstrating: Concerns, Decorators, and Presenters.
• Refactor Micropost Create Action (fat controller method)
Objectives
Patterns &
Techniques
14
DRY
Methods
< 5 Lines
Classes
< 100 lines
One Instance
Variable in View
Easy to
Test
Concerns
Draper
Decorators
Validation
Classes
Presenters
Split-up
Controllers
Clarity
Easy to
Change
Guidelines
Move Logic
to Models
Easy to
Find
Where we’re going with this talk…The first technique is Concerns.
• Huge model file with even larger spec file.	

• Break up the model/spec using Rails concerns.Try to break it
up by domain, but any logical split will help.
15
Scenario
If you will have multiple concerns for only one model, group the concerns inside of a module.
Scenario
• You’ve got duplicated code in two models, different database
tables.	

• Tease out a concern that applies to both models. Since your
models extend ActiveRecord::Base, using regular
inheritance is problematic. Instead, use a concern.
16
Rails Concerns
17
Big Model
class macros (has_many, validates, etc.)
instance methods
class methods
Rails Concerns
18
Big Model
some-domain class macros
some-domain instance methods
some-domain class methods
other class macros
other instance methods
other class methods
Domain Concern
some-domain
class macros
some-domain
instance methods
some-domain
class methods
Mix-ins on models and controllers. Mention controllers as well as models.
Concerns: How
• Discover set of related code for a problem domain
• Create a module with extends ActiveSupport::Concern	
• Move code into the Concern	

• Break out tests into corresponding test file for the Concern
19
Simple, safe, easy “refactoring”
You could use Ruby’s “include”, “included”, and “extend”…
But, not as simple
DHH on Domain vs. Technical Refactoring
"I’ve not yet found a case where the scope of the current file/
class couldn’t be brought under control by using a domain-driven
extraction approach."	

"In a sea of 60 methods, there will always be
domain-based groupings, rather than technical
groupings. Never seen that not be the case."
20
"There’s not going to be one solution to all big files. My preferred default is “break up using DOMAIN concerns
(not technical ones)”, unless there’s a “missing object” screaming to be liberated."
Concerns: Example
• Break out Emailable Concern out of User model	

• Captures domain logic of lower case emails on user model	

• Benefits: Smaller model, smaller spec
21
Objectives
Patterns &
Techniques
22
DRY
Methods
< 5 Lines
Classes
< 100 lines
One Instance
Variable in View
Easy to
Test
Concerns
Draper
Decorators
Validation
Classes
Presenters
Split-up
Controllers
Clarity
Easy to
Change
Guidelines
Move Logic
to Models
Easy to
Find
Where we’re going with this talk…
Scenario
• Model file creating detailed validation messages with HTML
tags and URL links.	

• Move the message creation code into a Draper Decorator for
the model.These decorators work great for model based
presentation code.
23
Draper Decorators
24
Mode and
Model-
Concerns
Presentation
Code (views,
helpers)
Draper Decorators
25
Mode and
Model-
Concerns
Presentation
Code (views,
helpers)
Draper
Decorators
Draper Decorators: What?
• Popular gem that facilitates model decorators	

• Very simple, easy to use
26
Draper Decorators: Why?
• Removing presentation code from your model or model-
concerns	

• Consolidating some helper, view, controller methods by models	

• Presentation code relating to one model, but multiple
controllers/views	

• Consolidation of flash messages related to a given model
27
Draper Decorators: Why
• Decorators are the ideal place to:	

• format complex data for user display	

• define commonly-used representations of an object, like a
name method that combines first_name and last_name
attributes	

• mark up attributes with a little semantic HTML, like turning a
url field into a hyperlink
28
Draper Decorators: Alternatives
• View Helpers	

• PORO, getting a handle to the controller or view
29
Example
Several views have code that format the micropost.created_at:	

!
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
30
Scenario
• You have duplicated rendering code in several files.	

• Remedy:	

1. If rendering code, use a partial.	

2. If ruby code, use either a view helper or create a static
method on a utility class. View helpers have access other
helpers. Utility classes require extra work to call view
context methods.
31
Objectives
Patterns &
Techniques
32
DRY
Methods
< 5 Lines
Classes
< 100 lines
One Instance
Variable in View
Easy to
Test
Concerns
Draper
Decorators
Validation
Classes
Presenters
Split-up
Controllers
Clarity
Easy to
Change
Guidelines
Move Logic
to Models
Easy to
Find
!
Scenario
• You are setting too many instance variables in the controller
action.You also have local variables being assigned in the view. 	

• Presenter pattern: Create a PORO that wraps up the values
and logic going from the controller to the view.
33
Scenario
• Fragment caching in your view, but some extra queries still run	

• Use the Presenter pattern, with memoization in the instance
methods.
• @foobar ||= calculate_foobar
34
Problem is the queries are invoked before the cache block.
Presenters
35
Presenter Object
Wrapping Data
Needed by View
Smaller Controller
Action Creating Only
the Presenter Instance
Big Controller
Action Setting
Many Instance
Variables
View with ONE
Instance Variable
View with MANY
Instance Variables
before
after
Scenario
• Problem:A controller file is huge with many actions and many more
private methods.	

• Solution:	

1. Split up the controller into multiple files by having your routing file
map to different controllers.	

2. Put any common functionality in a controller concern, similar to
how you would do it for a model.An alternative is having an
inheritance hierarchy of controllers. Mix-ins are more flexible.
36
Scenario
• Problem:	

• Your Presenter class needs to access the view context, but it’s PORO.	

• Solution:	

1. Use this include in your PORO: “include Draper::ViewHelpers”.	

2. Pass the controller instance into the constructor of the Presenter (include
required helpers in controller), or set the view context in the view file.	

3. Pass the view context into the methods that need it on the Presenter.
37
Objectives
Patterns &
Techniques
38
DRY
Methods
< 5 Lines
Classes
< 100 lines
One Instance
Variable in View
Easy to
Test
Concerns
Draper
Decorators
Validation
Classes
Presenters
Split-up
Controllers
Clarity
Easy to
Change
Guidelines
Move Logic
to Models
Easy to
Find
!
39
If a minor posts profane words:	

!
1. The post shall not be valid.	

2. A counter will track how many times the
minor tried to use profanity.	

3. The minor's parents shall be notified.	

4. A special flash alert will alert the minor to
profanity usage.
Business Case
Original Idea is to show refactoring to Service Objects!
–David Heinemeier Hansson
“I've yet to see a compelling "make action a
service object" example in the wild. Maybe
they exist somewhere, though. Then again,
maybe unicorns are real too.”
40
https://gist.github.com/dhh/10022098
Service Objects?
Service Objects Example
41
Big Micropost
Create Action
on Controller
MicropostCreationService
ControllerResponse
Flash, Flash-now, status code
Tiny Micropost
Create Action on
Controller
https://github.com/justin808/fat-code-refactoring-techniques/pull/6
before
after
Created class ControllerResponse to package up the return message from the “ServiceObject” to the controller.
Too much overlap with Controller!
A Bit Humbling…
DHH: "Sorry to keep shooting the patterns down, but this is
exactly what I mean when I say that most code does not need
patterns, it just needs to be rewritten better."	

JG: "I think it's a pattern either way.The pattern you presented is
to use validators rather than a separate object."	

DHH: Right, which Rails already has built in, and the code is
easier to follow with less work.
42
Single Purpose Controller
• Controller with only one action	

• https://github.com/justin808/fat-code-refactoring-techniques/
pull/7
43
Big Micropost
Create Action on
Controller
Micropost Controller
Just for Create
Rest of the
Micropost Controller
Left too much biz logic in controller
DHH on Controllers
“It’s [controller] intended to process the incoming request, fetch
the model, and direct the user to a view or another action. If
you’re yanking logic of that nature out of the controller, you’re
making an anemic controller. Shoving this into a
service object is imo the lazy approach that
doesn’t deliver any benefits in terms of
simpler code. It imo is the sweep-it-under-the-rug approach.
44
DHH on the work of a Controller
"I’ve yet to see compelling controller code that couldn’t be
slimmed down by simply writing it better, spinning off another
controller, or moving domain logic to the model. Here’s another
example of a code ping pong I did off a convoluted action in
RedMine: https://gist.github.com/dhh/10023987”
45
Plain Rails
46
Big Micropost
Create Action
on Controller
Micropost Model
User ModelSmall Micropost
Create Action on
Controller
before
after
MicropostController interacts with both models. No extra classes.
Move validation code and checks out of controller to model
Move creation of flash message to decorator
Move validation code to validation class
Scenario
• Excessive model logic in complicated controller method.	

• Either:	

• Move model logic out of controller and into the models,
utilizing Rails features such as validation.	

• Create a non-AR based model to handle an interaction
between two models (aka “Service Object”)
47
POR (Plain Old Rails)
• Use Rails Models,Validation, and Controller for their proper
jobs	

• KISS (Keep It Simple Stupid)	

• Don’t Invent Patterns That Don’t Need to be Invented	

• Know the why of the Rails way	

• Know the Rails way before deviating
48
Refactoring Steps
• Move validation code and checks out of controller to model	

• Move creation of flash message to decorator	

• Move validation code to validation class
49
References
• Rails Guides: http://guides.rubyonrails.org/	

• Patterns to Refactor Fat ActiveRecord Models: http://
blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-
fat-activerecord-models/	

• DHH’s Example of 2 Controllers with Concerns: https://
gist.github.com/dhh/10022098
50
Thanks!
Special thanks to those that helped review my code samples to this talk: @dhh,
@jeg2, @gylaz, @jodosha, @dreamr, @thatrubylove, @therealadam,
@robzolkos, Thoughtbot’s Learn program forum and Ruby Rogues Parley Forum
51
Rails on Maui HQ, aka Sugar Ranch Maui
Thanks!
• More details at my blog: 	

http://www.railsonmaui.com	

• Feel free to contact me
regarding your projects	

• justin@railsonmaui.com	

• http://airpair.me/railsonmaui
52

Weitere ähnliche Inhalte

Andere mochten auch

Making CLI app in ruby
Making CLI app in rubyMaking CLI app in ruby
Making CLI app in rubyHuy Do
 
Command Line Applications with Ruby
Command Line Applications with RubyCommand Line Applications with Ruby
Command Line Applications with RubyAlexander Merkulov
 
Improving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and UnicornImproving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and UnicornSimon Bagreev
 
Railsguide
RailsguideRailsguide
Railsguidelanlau
 
Introducing Command Line Applications with Ruby
Introducing Command Line Applications with RubyIntroducing Command Line Applications with Ruby
Introducing Command Line Applications with RubyNikhil Mungel
 
xUnit and TDD: Why and How in Enterprise Software, August 2012
xUnit and TDD: Why and How in Enterprise Software, August 2012xUnit and TDD: Why and How in Enterprise Software, August 2012
xUnit and TDD: Why and How in Enterprise Software, August 2012Justin Gordon
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with RubyAnis Ahmad
 
React on rails v6.1 at LA Ruby, November 2016
React on rails v6.1 at LA Ruby, November 2016React on rails v6.1 at LA Ruby, November 2016
React on rails v6.1 at LA Ruby, November 2016Justin Gordon
 
The Art of Product Marketing
The Art of Product MarketingThe Art of Product Marketing
The Art of Product MarketingRand Fishkin
 

Andere mochten auch (10)

Making CLI app in ruby
Making CLI app in rubyMaking CLI app in ruby
Making CLI app in ruby
 
Command Line Applications with Ruby
Command Line Applications with RubyCommand Line Applications with Ruby
Command Line Applications with Ruby
 
Improving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and UnicornImproving Your Heroku App Performance with Asset CDN and Unicorn
Improving Your Heroku App Performance with Asset CDN and Unicorn
 
Railsguide
RailsguideRailsguide
Railsguide
 
Introducing Command Line Applications with Ruby
Introducing Command Line Applications with RubyIntroducing Command Line Applications with Ruby
Introducing Command Line Applications with Ruby
 
React on rails v4
React on rails v4React on rails v4
React on rails v4
 
xUnit and TDD: Why and How in Enterprise Software, August 2012
xUnit and TDD: Why and How in Enterprise Software, August 2012xUnit and TDD: Why and How in Enterprise Software, August 2012
xUnit and TDD: Why and How in Enterprise Software, August 2012
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with Ruby
 
React on rails v6.1 at LA Ruby, November 2016
React on rails v6.1 at LA Ruby, November 2016React on rails v6.1 at LA Ruby, November 2016
React on rails v6.1 at LA Ruby, November 2016
 
The Art of Product Marketing
The Art of Product MarketingThe Art of Product Marketing
The Art of Product Marketing
 

Ähnlich wie Slides with notes from Ruby Conf 2014 on using simple techniques to create slimer, clearer models, controllers, and views in Ruby on Rails.

Dealing with Obese Models
Dealing with Obese ModelsDealing with Obese Models
Dealing with Obese ModelsRyan Brunner
 
Darius Šilingas and Rokas Bartkevicius: Agile Modeling: from Anti-Patterns to...
Darius Šilingas and Rokas Bartkevicius: Agile Modeling: from Anti-Patterns to...Darius Šilingas and Rokas Bartkevicius: Agile Modeling: from Anti-Patterns to...
Darius Šilingas and Rokas Bartkevicius: Agile Modeling: from Anti-Patterns to...Agile Lietuva
 
Advanced CSS Troubleshooting
Advanced CSS TroubleshootingAdvanced CSS Troubleshooting
Advanced CSS TroubleshootingDenise Jacobs
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklistMax Kleiner
 
The View - 30 proven Lotuscript tips
The View - 30 proven Lotuscript tipsThe View - 30 proven Lotuscript tips
The View - 30 proven Lotuscript tipsBill Buchan
 
How to build the perfect pattern library
How to build the perfect pattern libraryHow to build the perfect pattern library
How to build the perfect pattern libraryWolf Brüning
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean CodingMetin Ogurlu
 
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and InterfacesEpisode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and InterfacesJitendra Zaa
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General IntroductionAsma CHERIF
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agilityelliando dias
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tipsBill Buchan
 
AtlasCamp 2013: Confluence patterns
AtlasCamp 2013: Confluence patternsAtlasCamp 2013: Confluence patterns
AtlasCamp 2013: Confluence patternscolleenfry
 
Advanced oop laws, principles, idioms
Advanced oop laws, principles, idiomsAdvanced oop laws, principles, idioms
Advanced oop laws, principles, idiomsClint Edmonson
 

Ähnlich wie Slides with notes from Ruby Conf 2014 on using simple techniques to create slimer, clearer models, controllers, and views in Ruby on Rails. (20)

Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Restructuring rails
Restructuring railsRestructuring rails
Restructuring rails
 
Dealing with Obese Models
Dealing with Obese ModelsDealing with Obese Models
Dealing with Obese Models
 
Darius Šilingas and Rokas Bartkevicius: Agile Modeling: from Anti-Patterns to...
Darius Šilingas and Rokas Bartkevicius: Agile Modeling: from Anti-Patterns to...Darius Šilingas and Rokas Bartkevicius: Agile Modeling: from Anti-Patterns to...
Darius Šilingas and Rokas Bartkevicius: Agile Modeling: from Anti-Patterns to...
 
Advanced CSS Troubleshooting
Advanced CSS TroubleshootingAdvanced CSS Troubleshooting
Advanced CSS Troubleshooting
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Testing gone-right
Testing gone-rightTesting gone-right
Testing gone-right
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
 
The View - 30 proven Lotuscript tips
The View - 30 proven Lotuscript tipsThe View - 30 proven Lotuscript tips
The View - 30 proven Lotuscript tips
 
How to build the perfect pattern library
How to build the perfect pattern libraryHow to build the perfect pattern library
How to build the perfect pattern library
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and InterfacesEpisode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
 
Code quality
Code quality Code quality
Code quality
 
AtlasCamp 2013: Confluence patterns
AtlasCamp 2013: Confluence patternsAtlasCamp 2013: Confluence patterns
AtlasCamp 2013: Confluence patterns
 
Software Design
Software DesignSoftware Design
Software Design
 
Advanced oop laws, principles, idioms
Advanced oop laws, principles, idiomsAdvanced oop laws, principles, idioms
Advanced oop laws, principles, idioms
 
The Modlet Pattern
The Modlet PatternThe Modlet Pattern
The Modlet Pattern
 

Kürzlich hochgeladen

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Kürzlich hochgeladen (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Slides with notes from Ruby Conf 2014 on using simple techniques to create slimer, clearer models, controllers, and views in Ruby on Rails.

  • 1. R A I L S O N M A U I 1
  • 2. Concerns, Decorators, Presenters, Service Objects, Helpers, Help me Decide! RailsConf 2014 Chicago April 22, 2014 ! Justin Gordon @railsonmaui Rails Consultant www.railsonmaui.com 2
  • 4. Avoid the Ball of Mud May seem fun… ! Guaranteed: the perpetrator is not doing the cleanup! 4 • Show Redmine, • AccountsController, lost_password action • UserModel, big class, 762 Lines
  • 5. 5 Sandi Rules method > 5 lines class > 100 lines 😱
  • 6. 6 How do we organize the mess?
  • 7. Organizational Conventions Matter 7 Department Store What if the clothing store was organized by color? What if a clothing store was organized by size?
  • 8. Organizational Conventions Matter 8 Thrift Store What if no organization?
  • 9. Like Fashion… Coding Style ➜ Personal Preference 9 • Coding is like writing! • Tons of disagreement in the Rails community over names, patterns, etc. • But let’s agree on a few things..
  • 10. And Our Style is… 10 Prefer the Rails default framework (Models, Model Concerns, Controllers, Controller Concerns) Know Rails really well! Assume team members also know rails!
  • 11. DHH Quote JG: "This is starting to boil down to utilize the framework capabilities and move beyond only when necessary.” DHH: "Which is really just an extension of KISS (Keep It Simple, Stupid). When you use the framework code for what it’s intended, you’re not cutting against the grain. You don’t need to write as much code. It’s clearer to everyone because it’s the same approach everyone else is taking." 11
  • 12. Microposts Example 12 Micropost Model User Model Micropost Controller User Controller 1 N
  • 13. Refactoring Examples in Pull Requests • https://github.com/justin808/fat-code-refactoring-techniques/ pulls • Based on Michael Hartl’s “Rails Tutorial” MicroBlog example application 13 • Github PRs are the most AMAZING place to discuss code! • Clean up the Microblog code a little, demonstrating: Concerns, Decorators, and Presenters. • Refactor Micropost Create Action (fat controller method)
  • 14. Objectives Patterns & Techniques 14 DRY Methods < 5 Lines Classes < 100 lines One Instance Variable in View Easy to Test Concerns Draper Decorators Validation Classes Presenters Split-up Controllers Clarity Easy to Change Guidelines Move Logic to Models Easy to Find Where we’re going with this talk…The first technique is Concerns.
  • 15. • Huge model file with even larger spec file. • Break up the model/spec using Rails concerns.Try to break it up by domain, but any logical split will help. 15 Scenario If you will have multiple concerns for only one model, group the concerns inside of a module.
  • 16. Scenario • You’ve got duplicated code in two models, different database tables. • Tease out a concern that applies to both models. Since your models extend ActiveRecord::Base, using regular inheritance is problematic. Instead, use a concern. 16
  • 17. Rails Concerns 17 Big Model class macros (has_many, validates, etc.) instance methods class methods
  • 18. Rails Concerns 18 Big Model some-domain class macros some-domain instance methods some-domain class methods other class macros other instance methods other class methods Domain Concern some-domain class macros some-domain instance methods some-domain class methods Mix-ins on models and controllers. Mention controllers as well as models.
  • 19. Concerns: How • Discover set of related code for a problem domain • Create a module with extends ActiveSupport::Concern • Move code into the Concern • Break out tests into corresponding test file for the Concern 19 Simple, safe, easy “refactoring” You could use Ruby’s “include”, “included”, and “extend”… But, not as simple
  • 20. DHH on Domain vs. Technical Refactoring "I’ve not yet found a case where the scope of the current file/ class couldn’t be brought under control by using a domain-driven extraction approach." "In a sea of 60 methods, there will always be domain-based groupings, rather than technical groupings. Never seen that not be the case." 20 "There’s not going to be one solution to all big files. My preferred default is “break up using DOMAIN concerns (not technical ones)”, unless there’s a “missing object” screaming to be liberated."
  • 21. Concerns: Example • Break out Emailable Concern out of User model • Captures domain logic of lower case emails on user model • Benefits: Smaller model, smaller spec 21
  • 22. Objectives Patterns & Techniques 22 DRY Methods < 5 Lines Classes < 100 lines One Instance Variable in View Easy to Test Concerns Draper Decorators Validation Classes Presenters Split-up Controllers Clarity Easy to Change Guidelines Move Logic to Models Easy to Find Where we’re going with this talk…
  • 23. Scenario • Model file creating detailed validation messages with HTML tags and URL links. • Move the message creation code into a Draper Decorator for the model.These decorators work great for model based presentation code. 23
  • 26. Draper Decorators: What? • Popular gem that facilitates model decorators • Very simple, easy to use 26
  • 27. Draper Decorators: Why? • Removing presentation code from your model or model- concerns • Consolidating some helper, view, controller methods by models • Presentation code relating to one model, but multiple controllers/views • Consolidation of flash messages related to a given model 27
  • 28. Draper Decorators: Why • Decorators are the ideal place to: • format complex data for user display • define commonly-used representations of an object, like a name method that combines first_name and last_name attributes • mark up attributes with a little semantic HTML, like turning a url field into a hyperlink 28
  • 29. Draper Decorators: Alternatives • View Helpers • PORO, getting a handle to the controller or view 29
  • 30. Example Several views have code that format the micropost.created_at: ! Posted <%= time_ago_in_words(micropost.created_at) %> ago. 30
  • 31. Scenario • You have duplicated rendering code in several files. • Remedy: 1. If rendering code, use a partial. 2. If ruby code, use either a view helper or create a static method on a utility class. View helpers have access other helpers. Utility classes require extra work to call view context methods. 31
  • 32. Objectives Patterns & Techniques 32 DRY Methods < 5 Lines Classes < 100 lines One Instance Variable in View Easy to Test Concerns Draper Decorators Validation Classes Presenters Split-up Controllers Clarity Easy to Change Guidelines Move Logic to Models Easy to Find !
  • 33. Scenario • You are setting too many instance variables in the controller action.You also have local variables being assigned in the view. • Presenter pattern: Create a PORO that wraps up the values and logic going from the controller to the view. 33
  • 34. Scenario • Fragment caching in your view, but some extra queries still run • Use the Presenter pattern, with memoization in the instance methods. • @foobar ||= calculate_foobar 34 Problem is the queries are invoked before the cache block.
  • 35. Presenters 35 Presenter Object Wrapping Data Needed by View Smaller Controller Action Creating Only the Presenter Instance Big Controller Action Setting Many Instance Variables View with ONE Instance Variable View with MANY Instance Variables before after
  • 36. Scenario • Problem:A controller file is huge with many actions and many more private methods. • Solution: 1. Split up the controller into multiple files by having your routing file map to different controllers. 2. Put any common functionality in a controller concern, similar to how you would do it for a model.An alternative is having an inheritance hierarchy of controllers. Mix-ins are more flexible. 36
  • 37. Scenario • Problem: • Your Presenter class needs to access the view context, but it’s PORO. • Solution: 1. Use this include in your PORO: “include Draper::ViewHelpers”. 2. Pass the controller instance into the constructor of the Presenter (include required helpers in controller), or set the view context in the view file. 3. Pass the view context into the methods that need it on the Presenter. 37
  • 38. Objectives Patterns & Techniques 38 DRY Methods < 5 Lines Classes < 100 lines One Instance Variable in View Easy to Test Concerns Draper Decorators Validation Classes Presenters Split-up Controllers Clarity Easy to Change Guidelines Move Logic to Models Easy to Find !
  • 39. 39 If a minor posts profane words: ! 1. The post shall not be valid. 2. A counter will track how many times the minor tried to use profanity. 3. The minor's parents shall be notified. 4. A special flash alert will alert the minor to profanity usage. Business Case Original Idea is to show refactoring to Service Objects!
  • 40. –David Heinemeier Hansson “I've yet to see a compelling "make action a service object" example in the wild. Maybe they exist somewhere, though. Then again, maybe unicorns are real too.” 40 https://gist.github.com/dhh/10022098 Service Objects?
  • 41. Service Objects Example 41 Big Micropost Create Action on Controller MicropostCreationService ControllerResponse Flash, Flash-now, status code Tiny Micropost Create Action on Controller https://github.com/justin808/fat-code-refactoring-techniques/pull/6 before after Created class ControllerResponse to package up the return message from the “ServiceObject” to the controller. Too much overlap with Controller!
  • 42. A Bit Humbling… DHH: "Sorry to keep shooting the patterns down, but this is exactly what I mean when I say that most code does not need patterns, it just needs to be rewritten better." JG: "I think it's a pattern either way.The pattern you presented is to use validators rather than a separate object." DHH: Right, which Rails already has built in, and the code is easier to follow with less work. 42
  • 43. Single Purpose Controller • Controller with only one action • https://github.com/justin808/fat-code-refactoring-techniques/ pull/7 43 Big Micropost Create Action on Controller Micropost Controller Just for Create Rest of the Micropost Controller Left too much biz logic in controller
  • 44. DHH on Controllers “It’s [controller] intended to process the incoming request, fetch the model, and direct the user to a view or another action. If you’re yanking logic of that nature out of the controller, you’re making an anemic controller. Shoving this into a service object is imo the lazy approach that doesn’t deliver any benefits in terms of simpler code. It imo is the sweep-it-under-the-rug approach. 44
  • 45. DHH on the work of a Controller "I’ve yet to see compelling controller code that couldn’t be slimmed down by simply writing it better, spinning off another controller, or moving domain logic to the model. Here’s another example of a code ping pong I did off a convoluted action in RedMine: https://gist.github.com/dhh/10023987” 45
  • 46. Plain Rails 46 Big Micropost Create Action on Controller Micropost Model User ModelSmall Micropost Create Action on Controller before after MicropostController interacts with both models. No extra classes. Move validation code and checks out of controller to model Move creation of flash message to decorator Move validation code to validation class
  • 47. Scenario • Excessive model logic in complicated controller method. • Either: • Move model logic out of controller and into the models, utilizing Rails features such as validation. • Create a non-AR based model to handle an interaction between two models (aka “Service Object”) 47
  • 48. POR (Plain Old Rails) • Use Rails Models,Validation, and Controller for their proper jobs • KISS (Keep It Simple Stupid) • Don’t Invent Patterns That Don’t Need to be Invented • Know the why of the Rails way • Know the Rails way before deviating 48
  • 49. Refactoring Steps • Move validation code and checks out of controller to model • Move creation of flash message to decorator • Move validation code to validation class 49
  • 50. References • Rails Guides: http://guides.rubyonrails.org/ • Patterns to Refactor Fat ActiveRecord Models: http:// blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose- fat-activerecord-models/ • DHH’s Example of 2 Controllers with Concerns: https:// gist.github.com/dhh/10022098 50
  • 51. Thanks! Special thanks to those that helped review my code samples to this talk: @dhh, @jeg2, @gylaz, @jodosha, @dreamr, @thatrubylove, @therealadam, @robzolkos, Thoughtbot’s Learn program forum and Ruby Rogues Parley Forum 51 Rails on Maui HQ, aka Sugar Ranch Maui
  • 52. Thanks! • More details at my blog: http://www.railsonmaui.com • Feel free to contact me regarding your projects • justin@railsonmaui.com • http://airpair.me/railsonmaui 52