Easiest and fast way to decorate Ruby on Rails models. Compatible with Rails 5.0 and 4.2, 4.1, 4.0.
Decorator Pattern – What is it? Check it here:
Add this line to your application's Gemfile:
gem'light-decorator','~> 1.0.1'Create base class ApplicationDecorator in folder app/decorators/application_decorator.rb
rails g light:decorator:install
Create decorator for your model. For example we will use the User model.
We can manually create file:
# app/decorators/user_decorator.rbclassUserDecorator < ApplicationDecoratordeffull_name"#{object.first_name}#{object.last_name}"endendOr we can just use command to create this file:
rails g decorator User
Decorate your model in controller or anywhere.
# Single recordUser.find(params[:id]).decorateUser.find_and_decorate(params[:id])User.decorate.find(params[:id])# CollectionUser.all.decorateUser.decorateUser.limit(10).decorateUser.decorate.limit(10)# OptionsUser.find_and_decorate(params[:id],with: AnotherUserDecorator)# Associations will be decorated automaticallyuser=User.find_and_decorate(params[:id])user.decorated?# trueuser.comments.decorated?# trueuser.comments.first.decorated?# trueExample of Decorator
classUserDecorator < ApplicationDecoratordeffull_name"#{object.first_name}#{object.last_name}"# or"#{o.first_name}#{o.last_name}"enddeffull_name_linkhelpers.link_tofull_name,user_path(object)# orh.link_tofull_name,user_path(o)endend- Create installation generator
- Create decorator generator
- Create configuration file
Bug reports and pull requests are welcome on GitHub at https://github.com/light-ruby/light-decorator. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
The gem is available as open source under the terms of the MIT License.