Skip to content

DRY Rendering activities using ViewComponent #373

@Merovex

Description

@Merovex

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>&middot;</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}"

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions