Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
tslocke opened this issue Mar 8, 2016 · 2 comments
Open

Comments

@tslocke
Copy link

tslocke commented Mar 8, 2016

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
Copy link
Collaborator

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
Copy link
Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants