// Ruby on Rails Rails · Trailblazer · Architecture

Introduction to Trailblazer Through Decorators

6 min read · Ruby on Rails
Summary 6 min read

MVC leaves presentation logic with nowhere good to live, so it leaks into views and models. The Decorator pattern fixes that, and Trailblazer's Disposable::Twin makes decorators easy: expose only the properties a view needs, including nested ones, while keeping sensitive data out.

M.V.C., three letters with a lot of baggage. For the uninitiated, M.V.C. stands for Model-View-Controller. It’s design pattern for how to organize code for an application. It was made popular by Rails, but it definitely is not Rails specific. When mobile app development hit the scene, we started hearing of M.M.V.C. which stands for Model-Model View-Controller. At first, the new design pattern sounded like a distinction without difference to me, but that wasn’t because of the pattern itself but because how I approached MVC originally. Let’s dig into that a bit to see why.

In the MVC pattern, the model encapsulates the data (usually saved in a database) that represents a logical entity or a model of a physical entity (eg. user, organization, etc). The view determines how things are displayed to the user and what interactions the user can have with the application. The controller, like an air traffic controller at an airport, routes traffic through our app and determines what data to pull (models) and pass along to the appropriate view. Very simple, and it’s meant to help developers organize their code instead of trying to put everything in one file (I’m talking about you PHP!). Turns out, applications can get very complex, and the data can be relational (user owns a car, car has car insurance, etc) and those relationships can get very complicated really quickly. The view that is responsible for representing all those relationships and data can become riddled with view logic (many layers of if statements). Mobile applications, on the other hand, need to be very simplistic on the view layer because the screen is small, which forced mobile developers to add another layer in the design pattern called the View Model, which has the responsibility of taking the data we need for our view, encapsulate it and decide what can be shown and interacted with based on the context. It’s a good idea. I support that idea. So why did I think that it’s a distinction without difference? Simply because I thought we were already doing that with MVC. We already have the Decorator pattern that is essentially what model views are.

In theory, that is true. We already have a pattern in our toolbox that we should reach for, but we all know that many of us, including myself, don’t reach for it often enough. I bet you that the application you’re working on right now does not make use of the Decorator pattern, does it?

If don’t know about the Decorator pattern, or about how to implement one in Ruby, I highly recommend this article by the good folks at ThoughtBot. If you just want a gem, try draper. Or, if you are obsessed with code clarity and organization like I am, then look into something like trailblazer. Why trailblazer? Because I like the idea of grouping parts of an application into components, or concepts in the trailblazer lingo. Each component can be divided up into multiple parts, each of which is responsible for one thing and one thing only in your application. A user profile can have a form object that is responsible for collecting the data from the user and validating it, the contract takes that data and manipulates it then saves it, and a decorator retrieves that data and presents it back to the user ins a specific manner. The concept is the same, the user profile, the parts are independent and work can be done on each separately and without the risk of breaking any other part.

So what does trailblazer have to do with MVC and MVVC? Well the answer is on the trailblazer website, in the description:

Trailblazer gives you a high-level architecture for web applications. It extends the basic MVC pattern with new abstractions. Rock-solid conventions that go far beyond database table naming or route paths let you focus on your application code, minimize bugs and improve the maintainability.

In other words, trailblazer helps build on MVC and MVVC and structure real world apps in a very clean way. And one of the things it offers is decorators through what it calls a Disposable::Twin. Here’s how you would setup a user twin:

# app/concepts/user/view/user_twin.rb
class UserTwin < Disposable::Twin
  property :first_name
  property :last_name
  property :profile_image
end
twin = UserTwin.new(user)
twin.first_name # => delegates to user.first_name

There are few cool things it can do too:

# supports nesting
class OrgTwin < Disposable::Twin
  property :name
  property :owner do
    property :first_name
    property :last_name
  end
  # allows custom logic
  def display_name
    "Org: #{self.name}"
  end
end

and:

# lets you use dynamic/virtual attributes
class UserTwin < Disposable::Twin
  ...
  property :can_update_profile?, virtual: true
end
twin = UserTwin.new(user, can_update_profile?: current_user == user)
twin.can_update_profile? # => true if the logged in user is the same
                         # => false otherwise

or lets you reference doubly nested objects and expose them to the top:

class OrgTwin < Disposable::Twin
  feature Expose
  
  ...
  unnest :account, from: :owner
end
owner   = Owner.create(...)
account = Account.create(..., owner: owner)
org     = Org.create(..., owner: owner)
twin    = OrgTwin.new(org)
twin.account # => returns org.owner.account

assuming in the example above that you’ve setup a twin for the account that only exposes the type of account (pro, enterprise, etc) and leaves all the payment info out, you can see how it can be cleaner to display the profile of an organization without the need to litter your view with a bunch of logic and without passing it all the data that is encapsulated in the models (including passwords and other sensitive information).

There you go, not a lot of setup or fancy stuff that is required to get started making your application code a bit cleaner. The nice thing about trailblazer is that it’s modular and you can just use what you need and leave the rest behind. If you are just going to use the Decorator pattern, I recommend you go with the draper gem, otherwise be on the lookout for more posts from us on how to add other pieces of trailblazer to your app in the hopes of moving towards a much cleaner and maintainable code structure.

Bear & Giraffe Advisory

We partner with founders and tech leads to build sustainable Rails architecture, untangle monoliths, and scale pragmatic systems.

Schedule a Strategy Call
ESC

Type to search 38 posts