DRY Rendering activities using ViewComponent
Merovex opened this issue · comments
I would like to suggest view components as a curiously DRY way of rendering the activities. There's no need to create several view files in app/views/public_activity
.
Render Activities using ViewComponent
Install view component:
bundle add view_component
Create the view component
rails generate component Activity
In activity_component.rb
add
class ActivityComponent < ViewComponent::Base
def initialize(activity:)
@activity = activity
end
end
In the activity_component.html.erb
add
<article>
<div>
<h4>
<%= t(@object.key).html_safe % {target: @object.trackable.to_s} %>
</h4>
<div>
<span><%= @object.owner.to_s unless @object.owner.nil? %></span>
<span>·</span>
<%= @object.created_at %>
</div>
</div>
</article>
In the view add:
<% @activities.each do |activity|%>
<%= render ActivityComponent.new(activity:) %>
<% end %>
In the translation file add:
en:
post:
create: "Created post %{target}"
update: "Updated %{target}"
@Merovex Thanks for this. Indeed, I think something like that could be nice default. Though, I’d like to challenge the following assumption:
There's no need to create several view files in app/views/public_activity.
In an app I work on this is very much not true. However, that does not invalidate this idea.
Also, I’m not sure whether ViewComponent is justified given how little of it is used here but that might just be the MVP example code. As ViewComponent provides slots it could very well be a good idea to use it and allow passing a custom header and/or body.
Let me if you’re keen on working on a PR. Otherwise, I might try to finally look into it when I’m back from holiday.
Hi 👋
@Merovex have you been working on a PR for this by any chance?
I'm curious about how this feature would integrate in our project.
François