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.
gem 'deckorator'Then run bundler
$ bundleOr, install it yourself as
$ gem install deckoratorInclude Deckorator in the application controller
class ApplicationController < ActionController::Base
include Deckorator
endThen, run the install generator
$ rails g deckorator:installAn application decorator will be placed in app/decorators.
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
endclass UserDecorator < ApplicationDecorator
def full_name
if first_name.blank? && last_name.blank?
'Unnamed User'
else
"#{first_name} #{last_name}".strip
end
end
end$ rails g deckorator:decorator userThis will create a UserDecorator in the app/decorators directory while also generating a stubbed test.
You might want to add this to your app/decorators/ApplicationDecorator:
def self.policy_class
"#{decorated_object_class}Policy"
endclass UserDecorator < ApplicationDecorator
include ActionView::Helpers
def profile_card
content_tag_for(:div, decorated_object, class: :profile) do
gravatar_image(email)
end
end
endclass 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
endclass PostDecorator < ApplicationDecorator
def comments
Deckorator.decorate(decorated_object.comments)
end
endMIT
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request
Crafted with <3 by John Otander and Jake Mays.