SlideShare uma empresa Scribd logo
1 de 52
Baixar para ler offline
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
5
Sandi Rules
method > 5 lines
class > 100 lines
😱
6
How do we organize the mess?
Organizational Conventions Matter
7
Department Store
Organizational Conventions Matter
8
Thrift Store
Like Fashion…
Coding Style ➜ Personal Preference
9
And Our Style is…
10
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
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
• 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
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
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
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
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
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
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
–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
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
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
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

Mais conteúdo relacionado

Mais procurados

4 3-3 wide attacking patterns
4 3-3 wide attacking patterns4 3-3 wide attacking patterns
4 3-3 wide attacking patternsRyan Rich
 
Урок №9. Адресація в середовищі табличного процесора. Іменовані комірки і ді...
Урок №9. Адресація в середовищі  табличного процесора. Іменовані комірки і ді...Урок №9. Адресація в середовищі  табличного процесора. Іменовані комірки і ді...
Урок №9. Адресація в середовищі табличного процесора. Іменовані комірки і ді...Nikolay Shaygorodskiy
 
4 клас 8 урок. Копіювання і переміщення фрагментів тексту
4 клас 8 урок. Копіювання і переміщення фрагментів тексту4 клас 8 урок. Копіювання і переміщення фрагментів тексту
4 клас 8 урок. Копіювання і переміщення фрагментів текстуStAlKeRoV
 
Youth Tactical Training
Youth Tactical TrainingYouth Tactical Training
Youth Tactical TrainingRaúl Oliveira
 
Цикли з передумовою
Цикли з передумовоюЦикли з передумовою
Цикли з передумовоюrussoua
 
Математична модель
Математична модельМатематична модель
Математична модельt0hins
 
3 клас урок 13 що таке веб сторінки,веб-сайти та як їх переглядати.
3 клас урок 13 що таке веб сторінки,веб-сайти та як їх переглядати.3 клас урок 13 що таке веб сторінки,веб-сайти та як їх переглядати.
3 клас урок 13 що таке веб сторінки,веб-сайти та як їх переглядати.Сокальська ЗШ І-ІІІ ступенів №2
 
A Organização Dinâmica do Jogo de Futebol
A Organização Dinâmica do Jogo de FutebolA Organização Dinâmica do Jogo de Futebol
A Organização Dinâmica do Jogo de FutebolFundação Real Madrid
 
Inside Soccer The Development Phase
Inside Soccer  The Development PhaseInside Soccer  The Development Phase
Inside Soccer The Development PhaseMatthew Pearson
 
Periodização Tática - José guilherme 2016
Periodização Tática - José guilherme 2016Periodização Tática - José guilherme 2016
Periodização Tática - José guilherme 2016Fernando Farias
 
Manual de entrenamiento tareas condicionales real madrid cf
Manual de entrenamiento tareas condicionales real madrid cf Manual de entrenamiento tareas condicionales real madrid cf
Manual de entrenamiento tareas condicionales real madrid cf Elder Andrade
 
8 клас урок 10
8 клас урок 108 клас урок 10
8 клас урок 10pupilsShostka
 
O desenvolvimento do jogar
O desenvolvimento do jogarO desenvolvimento do jogar
O desenvolvimento do jogarFernando Farias
 

Mais procurados (20)

4 3-3 wide attacking patterns
4 3-3 wide attacking patterns4 3-3 wide attacking patterns
4 3-3 wide attacking patterns
 
6 klas
6 klas 6 klas
6 klas
 
6 клас урок 18
6 клас урок 186 клас урок 18
6 клас урок 18
 
Calcio scheda allenamento pulcini
Calcio scheda allenamento pulciniCalcio scheda allenamento pulcini
Calcio scheda allenamento pulcini
 
Урок №9. Адресація в середовищі табличного процесора. Іменовані комірки і ді...
Урок №9. Адресація в середовищі  табличного процесора. Іменовані комірки і ді...Урок №9. Адресація в середовищі  табличного процесора. Іменовані комірки і ді...
Урок №9. Адресація в середовищі табличного процесора. Іменовані комірки і ді...
 
Pretemporada
PretemporadaPretemporada
Pretemporada
 
El modelo de juego del FC Barcelona
El modelo de juego del FC BarcelonaEl modelo de juego del FC Barcelona
El modelo de juego del FC Barcelona
 
4 клас 8 урок. Копіювання і переміщення фрагментів тексту
4 клас 8 урок. Копіювання і переміщення фрагментів тексту4 клас 8 урок. Копіювання і переміщення фрагментів тексту
4 клас 8 урок. Копіювання і переміщення фрагментів тексту
 
Youth Tactical Training
Youth Tactical TrainingYouth Tactical Training
Youth Tactical Training
 
Цикли з передумовою
Цикли з передумовоюЦикли з передумовою
Цикли з передумовою
 
Урок 44. Цикл з післяумовою
Урок 44. Цикл з післяумовоюУрок 44. Цикл з післяумовою
Урок 44. Цикл з післяумовою
 
Histoire islam
Histoire islamHistoire islam
Histoire islam
 
Математична модель
Математична модельМатематична модель
Математична модель
 
3 клас урок 13 що таке веб сторінки,веб-сайти та як їх переглядати.
3 клас урок 13 що таке веб сторінки,веб-сайти та як їх переглядати.3 клас урок 13 що таке веб сторінки,веб-сайти та як їх переглядати.
3 клас урок 13 що таке веб сторінки,веб-сайти та як їх переглядати.
 
A Organização Dinâmica do Jogo de Futebol
A Organização Dinâmica do Jogo de FutebolA Organização Dinâmica do Jogo de Futebol
A Organização Dinâmica do Jogo de Futebol
 
Inside Soccer The Development Phase
Inside Soccer  The Development PhaseInside Soccer  The Development Phase
Inside Soccer The Development Phase
 
Periodização Tática - José guilherme 2016
Periodização Tática - José guilherme 2016Periodização Tática - José guilherme 2016
Periodização Tática - José guilherme 2016
 
Manual de entrenamiento tareas condicionales real madrid cf
Manual de entrenamiento tareas condicionales real madrid cf Manual de entrenamiento tareas condicionales real madrid cf
Manual de entrenamiento tareas condicionales real madrid cf
 
8 клас урок 10
8 клас урок 108 клас урок 10
8 клас урок 10
 
O desenvolvimento do jogar
O desenvolvimento do jogarO desenvolvimento do jogar
O desenvolvimento do jogar
 

Semelhante a Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, Help Me Decide-april-22-2014

Slides with notes from Ruby Conf 2014 on using simple techniques to create sl...
Slides with notes from Ruby Conf 2014 on using simple techniques to create sl...Slides with notes from Ruby Conf 2014 on using simple techniques to create sl...
Slides with notes from Ruby Conf 2014 on using simple techniques to create sl...Justin Gordon
 
Adding Another "M" to MVC: MVCM
Adding Another "M" to MVC: MVCMAdding Another "M" to MVC: MVCM
Adding Another "M" to MVC: MVCMMario Vargas
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeValerio Maggio
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General IntroductionAsma CHERIF
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
Refactoring workshop
Refactoring workshop Refactoring workshop
Refactoring workshop Itzik Saban
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2Knoldus Inc.
 
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
 
CS101- Introduction to Computing- Lecture 44
CS101- Introduction to Computing- Lecture 44CS101- Introduction to Computing- Lecture 44
CS101- Introduction to Computing- Lecture 44Bilal Ahmed
 
Refactoring, Therapeutic Attitude to Programming.
Refactoring, Therapeutic Attitude to Programming.Refactoring, Therapeutic Attitude to Programming.
Refactoring, Therapeutic Attitude to Programming.Amin Shahnazari
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP StackLorna Mitchell
 

Semelhante a Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, Help Me Decide-april-22-2014 (20)

Slides with notes from Ruby Conf 2014 on using simple techniques to create sl...
Slides with notes from Ruby Conf 2014 on using simple techniques to create sl...Slides with notes from Ruby Conf 2014 on using simple techniques to create sl...
Slides with notes from Ruby Conf 2014 on using simple techniques to create sl...
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Adding Another "M" to MVC: MVCM
Adding Another "M" to MVC: MVCMAdding Another "M" to MVC: MVCM
Adding Another "M" to MVC: MVCM
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing code
 
Code coverage
Code coverageCode coverage
Code coverage
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Clean Code V2
Clean Code V2Clean Code V2
Clean Code V2
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Refactoring workshop
Refactoring workshop Refactoring workshop
Refactoring workshop
 
Code quality
Code quality Code quality
Code quality
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2
 
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
 
CS101- Introduction to Computing- Lecture 44
CS101- Introduction to Computing- Lecture 44CS101- Introduction to Computing- Lecture 44
CS101- Introduction to Computing- Lecture 44
 
Refactoring, Therapeutic Attitude to Programming.
Refactoring, Therapeutic Attitude to Programming.Refactoring, Therapeutic Attitude to Programming.
Refactoring, Therapeutic Attitude to Programming.
 
Software Design principales
Software Design principalesSoftware Design principales
Software Design principales
 
Anti patterns part 2
Anti patterns part 2Anti patterns part 2
Anti patterns part 2
 
Bdd with m spec
Bdd with m specBdd with m spec
Bdd with m spec
 
Tool up your lamp stack
Tool up your lamp stackTool up your lamp stack
Tool up your lamp stack
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP Stack
 
Ds for finance day 4
Ds for finance day 4Ds for finance day 4
Ds for finance day 4
 

Último

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 

Último (20)

TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 

Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, Help Me Decide-april-22-2014

  • 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
  • 5. 5 Sandi Rules method > 5 lines class > 100 lines 😱
  • 6. 6 How do we organize the mess?
  • 9. Like Fashion… Coding Style ➜ Personal Preference 9
  • 10. And Our Style is… 10
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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