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

Automatically use decorated associations in delegate methods #917

Closed
jcat4 opened this issue Mar 31, 2022 · 1 comment
Closed

Automatically use decorated associations in delegate methods #917

jcat4 opened this issue Mar 31, 2022 · 1 comment

Comments

@jcat4
Copy link

jcat4 commented Mar 31, 2022

(sorry in advance if I missed an issue or something in the docs)

Let's say I have two model classes, Book and Author.
Book implements an author_name method that delegates name to its author.

class Book < ApplicationRecord
  belongs_to :author

  def author_name
    author.name
  end
end

class Author < ApplicationRecord
  has_many :books
end

My goal is to achieve something like this

book = Book.last
puts book.name # lord of the rings
puts book.author_name # j. r. r. tolkien

puts book.decorate.name # Lord of the Rings
puts book.decorate.author_name # J. R. R. Tolkien

I'd love to be able to do something like this

  class Book < Draper::Decorator
    delegate_all
    
    # book.decorate.author_name will automatically use a decorated author
    decorates_association :author

    ...
end

However, it does not work that way. A decorated book still sends name to an un-decorated author. So, I need to explicitly re-define the delegate method in the decorator in order to have book.decorate.author_name use a decorated author...

  class Book < Draper::Decorator
    delegate_all
    decorates_association :author
    
    # code duplication... :(
    def author_name
      author.name
    end
    
    ...
  end

If and when more delegate methods to author are defined on Book, this problem will only get nastier.

I haven't found a solution that does not involve duplicating code or violating the Law of Demeter.
Is there a cleaner way to implement this?

Thanks!

@jcat4
Copy link
Author

jcat4 commented Sep 8, 2022

No longer need a solution here

@jcat4 jcat4 closed this as completed Sep 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant