Created
June 12, 2019 17:03
-
-
Save krzkrzkrz/163b8b23744498555067139038dd9b6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Decorators | |
class BaseDecorator < SimpleDelegator | |
attr_reader :view | |
def initialize(model, view = ActionView::Base.new) | |
@view = view | |
super(model) | |
end | |
def self.from_collection(collection, view = ActionView::Base.new) | |
collection.map { |model| new(model, view) } | |
end | |
def model | |
__getobj__ | |
end | |
def inspect | |
"#{self.class}(#{super})" | |
end | |
def method_missing(meth, *args) | |
if job_order.respond_to?(meth) | |
job_order.send(meth, *args) | |
else | |
super | |
end | |
end | |
end | |
class ArticleDecorator < BaseDecorator | |
def user | |
@user ||= UserDecorator.new(super) | |
end | |
def foo | |
@foo ||= 'foo' | |
end | |
end | |
class UserDecorator < BaseDecorator | |
def bar | |
@bar ||= 'bar' | |
end | |
end | |
# Controller | |
article = Article.find(..) | |
@article = ArticleDecorator.new(article) | |
# View | |
<%= @article.foo %> <-- Returns 'foo' | |
<%= @article.user.bar %> <-- Renders high CPU, nothing happens. I suspect an infinite loop somewhere | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment