draper
draper copied to clipboard
Automatically use decorated associations in delegate methods
(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!
No longer need a solution here