Thoughts on the decorator pattern

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the architecture category.

Last Updated: 2024-11-23

I showed J my ProductController in Rails, which was as follows:

def show
  cache_publicly

  @notes_file_count = product.notes_files.count
  @author_count = product.notes_files.pluck(:author).uniq.count
  @average_page_count = average_page_count(@author_count)
  @sale_count = @product.sales.count
  @hit_count = Traffic.new.hits_to_product(@product.id)
  @sale_rank = SaleRank.new.of_product(@product)
  @satisfaction_percentage = satisfaction_percentage
  @bundle_product = @product.bundle_product

  @notes_files = @product.notes_files.with_attached_sample.with_attached_image
    .reorder(released_on: :desc).limit(15)
  render :show
end

private

def satisfaction_percentage
end
def average_page_count
end

I lamented the number of instantiations within and he suggested I look into what we called a presenter pattern (but I myself might name "an assembler" pattern) such that I have one instatiation.

class IndividualProductPresenter
  def sales_rank
  end

  def average_page_count
  end

  def notes_files
  end
end

Evaluating

Pros

Cons

Resources