Reflection to Tealeaf Course3 Week7 (2/3)
#Beyond MVC
Rails built on MVC (Model / View / Controller) structure. And something get complex if we got more code and logic. This is why we need design patterns.
##Decorators
Some tips from gem Draper
:
Without Draper, this functionality might have been tangled up in procedural helpers or adding bulk to your models. With Draper decorators, you can wrap your models with presentation-related logic to organise - and test - this layer of your app much more effectively.
Or
Decorators are the ideal place to:
- format complex data for user display
- define commonly-used representations of an object, like a
name
method that combinefirst_name
andlast_name
attributes.- mark up attributes with a little semantic HTML, like turning a url fiedl into a hyperlink.
First, install gem
1 | gem 'draper' |
1 | class VideoDecorator < Draper::Decorator |
And use it in controller
1 | def show |
In view, just a clear line code.
1 | = @video.rating |
The key point here is that we have a model data (rating) associated with view, it’s not suitable to put to view helper
(some logic with model). That’s why here using decorator to encapsulate presentation logic.
##Policy Objects
Define what is premium user:
1 | class UserLevelPolicy |
In Controller
1 | ###some code |
Different with Decorators, Policy Ojbects only concern judgement logic into one place, without presentation concerned.
##Domain Objects
if User
has an attribute credit_balance
. Then merge those code relative to credit
into Domain Object.
1 | class Credit |
Thus Credit.new(current_user)
can call methods about credit, and don’t need to put these code in model User
, or UsersController
.
##Service Objects
We abstract an action as sign up
in UsersController#create
.
1 | class UsersController < ApplicationController |
Then create an service object UserSignup
to handle this.
1 | class UserSignup |
There is an article from Code Climate 7 Patterns to Refactor Fat ActiveRecord Models
As it metion when to use Service Object:
- The action is complex (e.g. closing the books at the end of an accounting period)
- The action reaches across multiple models (e.g. an e-commerce purchase using Order, CreditCard and Customer objects)
- The action interacts with an external service (e.g. posting to social networks)
- The action is not a core concern of the underlying model (e.g. sweeping up outdated data after a certain time period).
- There are multiple ways of performing the action (e.g. authenticating with an access token or password). This is the Gang of Four Strategy pattern.
##Some Concept for Object Oriented Design
Fat model, skinny controllers
makes model uncontrollrable. That’s why we need Object Oriented DesignYAGNI
YAGNI means You Aren't Gonna Need It!
Don’t write the code you haven’t need it.
Here is aother post talking about YAGNI
, KISS
, DRY
.
Software Development: KISS, YAGNI & DRY. 3 Principles to simplify your life.