design-pattern

In this article, we learned about another Ruby On Rails Design Pattern – Decorators

The decorator is a design pattern that allows the behavior to be added to an object, dynamically, without disturbing the behavior of other objects of the same class. Decorators can be useful for cleaning up logic/code written inside the view and controller in a Rails application.

‘In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.’

https://en.wikipedia.org/wiki/Decorator_pattern

The process to achieve the Decorator Design Pattern

(1) Create an app/decorator folder.

(2) Add decorate helper in ApplicationHelper.

module applicationHelper
  def decorate(model_name, decorator_class = nil)
  (decorator_class || "#{model_name.calss}Decorator".constantize).new(model_name)	
 end
end

(3) Add base_decorator.rb in app/decorators folder

class BaseDecorator < SimpleDelegator
  def decorate(model_name, decorator_class = nil)		 
    ApplicationController.helpers.decorate(model_name, decorator_class)
  end
end

(4) Add user_decorator.rb in app/decorators folder.

Class UserDecorator < BaseDecorator
  def full_name
    "#{fname} #{lname}"
  end
end

(5) Initialize @user_decorator in your user_controller.

Class UsersController < ApplicationController
  def show
    @user_decorotor = helpers.decorate(current_user)
  end
end

(6) Let’s use this in our view(show.html.erb).

<%= @user_decorator.full_name %>
<%= @user_decorator.email %>

Concluson:

The decorator pattern is used, where we are trying to avoid duplicate code & crazy class names.

Leave a Reply

Your email address will not be published. Required fields are marked *