drapergem / draper

Decorators/View-Models for Rails Applications
MIT License
5.23k stars 527 forks source link

Suggestion: add context[:owner] automatically for decorated associations #731

Open tslocke opened 8 years ago

tslocke commented 8 years ago

Imagine a stock portfolio app where a user has_many companies. Say I want to list the value of a user's portfolio broken down by company.

I could add a method portfolio_value(user) to the company decorator, and do

<% user.companies.each do |company| %>
  <li><%= company.name %>: <%= company.portfolio_value(user) %>
<% end %>

But given I accessed the company via user.companies, the user could already be available in the context of the company decorator, and I could do simply:

<% user.companies.each do |company| %>
  <li><%= company.name %>: <%= company.portfolio_value %>
<% end %>

In my experience this is a common pattern in many apps.

A simple monkey patch to achieve this is:

class Draper::DecoratedAssociation

  def call
    decorate unless defined?(@decorated)
    @decorated.context[:owner] = @owner
    @decorated
  end

end

I've been using this patch and found it very useful. If the maintainers think this would make a good enhancement to Draper I would be happy to submit a PR.

Alexander-Senko commented 1 month ago

If the maintainers think this would make a good enhancement to Draper I would be happy to submit a PR.

I do think so. If we already have context there, this add-on is going to add no more complexity, I guess, nor should it interfere with anything 🤔

We should still respect context[:owner] if one has been passed explicitly.

Alexander-Senko commented 1 month ago

I'm sorry for the answer taking so long. I'm quite new here, trying to dig through all the issues.