🚀 I create the
dekoratorgem if this interrest you.
Copy ApplicationDecorator inside app/decorators/application_decorator.rb and DecoratorsHelper inside decorators_helper.rb.
Then you could create and use your own decorators by create new class that extend from ApplicationDecorator.
class PostDecorator < ApplicationDecorator
include ActionView::Helpers::TextHelper
decorates_association :comments
# OR
# decorates_association :comments, with: CommentDecorator
def title
title.upcase_first
end
def summary
truncate(body, length: 170)
end
end
class CommentDecorator < ApplicationDecorator
def commented_at
"commented at #{l(created_at)}"
end
endTo decorate a model, you have to use ApplicationDecorator#decorate. This method is accessible in your view with #decorate.
decorated_post = decorate(@post)
decorated_post = decorate(@post, with: PostDecorator)
decorate(@post) do |decorated_post|
# use decorated_post here
end<% @post = decorate(@post) %>
<h1><%= @post.title %></h1>
<p><%= @post.summary %></p>
<% @post.comments.each do |comment| %>
<p><b><%= comment.commented_at %></b></p>
<% end %>