Draper is a really cool gem that utilizes the decorator rails pattern. You can extract logic from views and view helpers and convert them into objects.
For a simple explanation, lets view this codeblock for a todo list in rails.
<h4>Todo <%= @todo.content %> Created on <%= @todo.created_at %> </h4>
Generated: TODO - Make cool stuff in ruby. Created on ‘2019-07-02 15:22:41’
This is boring, unappealing and will make your rails app UNDRY!
So how can a decorator help your application? Let’s start by install and running the same rails commands like always:
#Gemfile gem 'draper'
#terminal bundle install
Now we are going to generate a decorator to wrap our
Todo model. This will create the directory
app/decorators in your application.
rails g decorator Todo
Now locate your Todo controller show method and add the following:
def show tem = Todo.find(params[:id]) @todo = TodoDecorator.new(item) end
We have our setup going, but what are we trying to dry? In toy apps I’ve made before I’ve done things like formatting time, but across the app I’ve copied and pasted so many lines of code that it becomes a chore and a hassel to format them all. Our fancy decorator allows us to turn this logic into an object like so:
def formatted_created_at todo.created_at.strftime("%m/%d/%Y - %H:%M") end
and in our view we can compare the final decorated view line to the undecorated
#index.html.erb #Decorated <h4>Published <%= @article.strftime("%m/%d/%Y - %H:%M" %></h4> #Undecorated <h4>Todo <%= @todo.content %> Created on <%= @todo.created_at %> </h4>