Project

deckorator

0.0
No commit activity in last 3 years
No release in over 3 years
Lightweight decorators using plain old Ruby objects.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 3.0.0
~> 1.11
~> 10.0
~> 3.0

Runtime

 Project Readme

deckorator Build Status

Deckorator is a PORO (plain old Ruby object) implementation of the Decorator pattern. It can be easily integrated into Rails/Sinatra apps or any other Ruby project.

Installation

gem 'deckorator'

Then run bundler

$ bundle

Or, install it yourself as

$ gem install deckorator

With Rails

Include Deckorator in the application controller

class ApplicationController < ActionController::Base
  include Deckorator
end

Then, run the install generator

$ rails g deckorator:install

An application decorator will be placed in app/decorators.

Usage

Using the decorate method in the controller

class UsersController < ApplicationController
  before_action :set_user

  def show
    @user = decorate(@user)
  end

  private

  def set_user
    @user = User.find(params[:id])
  end
end

Example decorator

class UserDecorator < ApplicationDecorator
  def full_name
    if first_name.blank? && last_name.blank?
      'Unnamed User'
    else
      "#{first_name} #{last_name}".strip
    end
  end
end

There's a generator

$ rails g deckorator:decorator user

This will create a UserDecorator in the app/decorators directory while also generating a stubbed test.

Also using Pundit?

You might want to add this to your app/decorators/ApplicationDecorator:

def self.policy_class
  "#{decorated_object_class}Policy"
end

Add view helpers to your decorators

class UserDecorator < ApplicationDecorator
  include ActionView::Helpers

  def profile_card
    content_tag_for(:div, decorated_object, class: :profile) do
      gravatar_image(email)
    end
  end
end

Include Rails path helpers

class UserDecorator < ApplicationDecorator
  include Rails.application.routes.url_helpers
  include ActionView::Helpers

  def full_name_link
    link_to(full_name, user_path(decorated_object), class: 'btn btn-primary')
  end
end

Decorate associations

class PostDecorator < ApplicationDecorator
  def comments
    Deckorator.decorate(decorated_object.comments)
  end
end

Related

License

MIT

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Crafted with <3 by John Otander and Jake Mays.