draper icon indicating copy to clipboard operation
draper copied to clipboard

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

Open tslocke opened this issue 10 years ago • 2 comments

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.

tslocke avatar Mar 08 '16 17:03 tslocke

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 avatar Sep 10 '24 15:09 Alexander-Senko

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

Alexander-Senko avatar Sep 10 '24 15:09 Alexander-Senko