active_decorator gem

Keep helpers and views object-oriented by decorate model


source code


Quick start


add gem to gemfile


gem 'active_decorator'

Then

bundle install


Create a simple model

I called it Author with 2 attributes, first_name and last_name


rails generate model Author first_name last_name

run migration

rails db:migrate


Let's generate Authors controller


rails generate Authors index show

this command will create a AuthorsController along with action :index, and :show

We need to have some sample data for authors table before decorate it using active_decorator.


Let's open db/seeds.rb


authors = [
  { first_name: "John", last_name: "Doe" },
  { first_name: "Jane", last_name: "Thomson" },
  { first_name: "Darren", last_name: "Lee" }
]

Author.create(authors)


rails db:seed

Let's check if authors are persisted into database


rails runner "pp Author.all"


You will see something like this



That's a good start 🎉


Now, create AuthorDecorator


rails generate decorator Author

and implement a method call full_name by concatenate first_name and last_name together.


so in our decorator module, would look something like this

module AuthorDecorator
  def full_name
    "#{first_name} #{last_name}"
  end
end

Almost, finish!


Let's call it in view template app/views/authors/index.html.erb

<ul>
  <% @authors.each do |author| %>
    <li>First name: <%= author.first_name %></li>
    <li>Last name: <%= author.last_name %></li>
    <li>Last name: <%= author.full_name %></li>
  <% end %>
</ul>


Don't forget to update your AuthorsController as well

class AuthorsController < ApplicationController
  def index
    @authors = Author.all
  end


  def show
  end
end


Restart your web server to make sure everything loaded.

then reload your web browser.


You will see full_name is printed.


Learning by practicing,

Tweak your code and see result.

If you get errors, googling.

That is life of developers


Example:

https://github.com/radinreth/active-decorator-rails