许多演示者都有以下形式
class MyClassPresenter < SimpleDelegator
def something_extra
end
end
view_obj = MyClassPresenter.new my_class_instance
我想横向的实例:
view_obj.nested_obj.nested_obj.value
这意味着创建多个演示对象,它们实际上只是开始复制模型。
class MyClassPresenter < SimpleDelegator
def something_extra
end
def nest_obj
AnotherPresenter.new(__get_obj__.nest_obj)
end
end
更好地展示一个真实世界的例子
class UserPresenter < SimpleDelegator
def home_page_url
"/home/#{__get_obj__.id}"
end
end
class MyController < ApplicationController
def show
@user = UserPresenter.new(current_user) # devise's current_user
end
end
/my/show.html.slim
/! Show profile comments
- for comment in @user.profile.comments
| Comment on:
= comment.created_at
= comment.content
传入的主要对象是@user,但是,演示者并没有涵盖那么远。我可以创建@comments,但我希望代码更灵活,但前端工程师想要接受它。
其他人如何为演示者处理多个层次?
代码看起来像这样吗?(啊)
/! Show profile comments
- for comment in @user.profile.comments
- display_comment = CommentPresenter.new(comment)
| Comment on:
= display_comment.comment.created_at
= display_comment.content
-丹尼尔