Tuesday, 16 December 2014

12 Tips of Christmas - 6 Decorators

One of the really nice things about working with Ember is that every part nicely encapsulates it's level of responsibility. With Rails, this can be a harder proposition, especially when dealing with the view layer. Decorators can alleviate this issue and form our 6th, valuable tip.
We can utilise decorators to move view related logic out of the model, or helper and into the decorator object, we can do this, using SimpleDelegator.
SimpleDelegator accepts an object as part of it's instantiation, and if it can't find a method it will delegate to the underlying object.
class UserDecorator < SimpleDelegator
  def full_title
    "#{title} #{first_name} #{last_name}"
  end
end


class UsersController < ApplicationController
  def show
    @user = UserDecorator.new(User.find(params[:id])
  end
end
Using decorators as a view object, is a very simple option for moving logic out of the business layer that is the model.
Extending this concept, methods within the model that don't explicitly relate to business logic can be moved out and repurposed in a decorator.
class UsersController < ApplicationController
  def index
    @users = UsersDecorator.new(User.all).latest_users
  end
end
The question of where and when to extract this logic, should be dictated by whether or not it falls outside of the responsibility of the object you might decorate it with. I'm a big believer in trying to adhere to Single Responsibility Principle, so this extraction makes a lot of sense.
We want to utilise SimpleDelegator rather than sub-classing our objects as we're not really interested in copying or exposing the base classes API, we just want to copy functionality.

No comments:

Post a Comment