Yesterday we broke the entire dashboard into a component. This can make sense to apply to all the subcomponents of a page, the posts list in this case:
class PostList
def posts
Post
.where(publish_at: [..Time.current])
.order(publish_at: :desc)
.limit(10)
end
def to_partial_path
"posts/post_list"
end
end
class Dashboard
def post_list
PostList.new
end
end
<!-- app/views/posts/post_list.html.erb -->
<ul>
<%= dashboard.comments.each do |comment| %>
<li><%= link_to comment.body,
post_path(comment.post_id, anchor: dom_id(comment))
%></li>
<% end %>
</ul>
<!-- app/views/dashboards/dashboard.html.erb -->
<div>
<h2>Recent Comments</h2>
<%= render dashboard.post_list %>
</div>
Where this can provide a lot of benefit is if you add additional customization to the PostsList
class, filtering, sorting, and searching for example. You could easily reuse this and be able to make calls like:
PostList.new(search: "something")
PostList.new(limit: 25)
PostList.new(order: :title)
PostList.new(related_to: @current_post, limit: 3)
PostList.new(partial: "posts/inline_post")
Overall this keeps your controllers smaller and more focused, leaves you with testable page objects, and keeps your customizations focused and discrete.