[Rails] Organize your code neatly with gem active_decorator

background

-When I wrote calculations such as the total value and average value of columns in the view, it became confusing and difficult to read. -To solve the problem whether to write in view or controller

Introduction

First, add it to the gemfile.

gem 'active_decorator'

bundle install.

$ bundle install

Generate decorator file

Next, create a decorator file. This time it's about a model called score. Please use any name you like for the score part.

$ rails g decorator score

Then it will generate a file like this. app/decorators/score_decorator.rb

This time it was a golf score, so let me calculate the total of 18H.

module ScoreDecorator
  def total_score
    format('%+d', hole1_score.to_i + 
                  hole2_score.to_i + 
                  hole3_score.to_i +
・
・
・
                  hole18_score.to_i)
  end
end

Output in view

Now the view is clean!

  <% @scores.each do |score| %>
        <%= score.total_score %>
  <% end %>

Recommended Posts

[Rails] Organize your code neatly with gem active_decorator
Clean your code with Butter Knife
Generate Dart client code with Rails + apipie
[Rails] Let's manage constants with config gem
[Rails] Gem Rubocop Static code analysis tool
Bundle install with docker + rails6 does not reflect gem
Write beautiful code with indentation in mind (rails, html)
Call your own class created under lib with Rails
[Rails] Put together the same code with controller actions