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
- 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.