Hey πβ¨
During the past few months, I've been working on a back-end project made with Ruby on Rails. Last year I was working as a Front-End developer, I've never had the opportunity to apply design patterns almost anywhere, until now.
It's a pretty useful thing, that probably every developer that works with objects should at least know and practice, and this is why I'm here, to give you (and me!) a daily short post about the different design patterns that exist (or at least, those that are used the most), with an example, and an explanation.
Because doing good code will help you, your workmates, and those who will be in the future.
This day, I'll tell you about another interesting pattern that has been around for a long time. It is called View Object Pattern (aka. Presenter)
Having logic in our views is a reaaally bad idea. This would make views testing a real pain in the (add your favorite word here), and it's extra work that no one likes. Also, your views should always have as little embedded dynamic code as possible.
You'll be able to get rid of these two problems by applying the View Object pattern (You may also have heard about MVP pattern, which is pretty similar).
To generate a view object, you have to create a new class. Inside this new class, you will get anything you need from your model or controller, and you will do all the logic you had in your views, for example, retrieving all the users with that specific name you want.
Let me explain the example before you read it. We are creating a class to manage the logic for a discussion view, and we want to generate the user name and a timestamp of when the user wrote something. To do that, we will move the logic into our new View Object, and we'll call this method, just as it's shown below.
class DiscussionViewObject | |
attr_reader :discussion | |
delegate :name, :created_at, to: :discussion | |
def initialize(discussion) | |
@discussion = discussion | |
end | |
def name_with_time | |
@_name_with_time ||= created_at.strftime('%Y/%m/%d') + name | |
end | |
end |
Things you need to have in mind when working with views:
- Use Law of Demeter, only one dot functions.
- Donβt hit database in views, please!
- Views are not for the logic, do not assign variables here.
Now, in our controller, we can initialize the object and call it, making both the order logic and the dashboard initialization easier to read, just like this:
<div class="discussion-item"> | |
<%= discussion.name_with_time %> | |
</div> |
Now, your view now looks β¨ shiny and clean β¨
And this is my second article about design patterns for the series "A pattern a day keeps the reviewers away".
I'll try to keep posting every day one of the different patterns that are around. I can't promise I'll fulfill this task every day though!
You can read more about this pattern at:
Also, you can follow me so you are tuned to whenever I post something through my Twitter account!
Top comments (0)