Rails - moving out calculations from my views?

后端 未结 2 1086
悲哀的现实
悲哀的现实 2021-02-20 15:59

Currently I\'m performing some calculations in my views, which is a bad thing, of course:

<% categories.each do |c| %>
  ....
    <%= c.transactions.sum         


        
2条回答
  •  遇见更好的自我
    2021-02-20 16:57

    One mean to isolate view logic is to use presenters.

    A presenter allows you to do something like that :

    <% categories.each do |c| %>
      ....
        <% present c do |category| %>
        <%= category.transaction_sum %>
        <% end %>
      ....
    <% end %>
    

    You then have a presenter class in app/presenters/category_presenter.rb :

    class CategoryPresenter < BasePresenter
      presents :category
    
      def transaction_sum
        category.transactions.sum("amount_cents")
      end
    end
    

    Of course, it is best used if you have many methods in that presenter (but once you begins to reduce view logic, it's quick to fill presenters).

    The implementation used here rely on what is describe in this pro railscast. The basic idea is simply to have a #present helper that infers a class name based on object class, load and initialize the proper presenter class.

    An other popular alternative is to use drapper, which use the concept of decorator, but a presenter is basically a decorator.

提交回复
热议问题