Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save secretpray/6451fdfb84476bb40b824cf2a4065aff to your computer and use it in GitHub Desktop.
Save secretpray/6451fdfb84476bb40b824cf2a4065aff to your computer and use it in GitHub Desktop.
Check user_signed_in? and Is_author in Turbo Stream broadcasts
  1. Generate Stimulus controller
bin/rails g stimulus object_author
  1. app/javascript/controllers/object_author_controller.js
import { Controller } from '@hotwired/stimulus'

export default class extends Controller {
  static values = {
    authorId: String
  }

  connect() {
    if (this.currentUserId === this.authorId) {
      this.element.classList.remove("hidden")
    }
  }

  get authorId() {
    return this.authorIdValue
  }

  get currentUserId() {
    return document.querySelector("[name='current-user-id']").content
  }
}
  1. app/views/layouts/application.html.erb

  <meta name="current-user-id" content="<%= current_user&.id %>">
  1. Add controller name and action to template that will be broadcast by Turbo Stream:

app/views/posts/_post_brc.html.erb

. . .

<div class="flex items-center hidden"
           data-controller="object-author"
           data-object-author-author-id-value="<%= post.user.id %>">

  # Actions to be authorized using the controller.
  <%= link_to edit_post_path(post), data: { turbo_frame: :modal },
                                    class: "mr-2 text-yellow-400 opacity-50 hover:text-yellow-500 text-md hover:opacity-100"  do %>
    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
      <path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
    </svg>
  <% end %>
  <%= button_to post_path(post), method: :delete, data: { confirm: "Are you sure you want to delete this post?" },
                            class: "mr-2 text-yellow-400 opacity-50 hover:text-yellow-500 text-md hover:opacity-100" do %>
    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mt-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
     </svg>
   <% end %>

</div>

PS Broadcasting Turbo Stream Template from Resource Model:

after_create_commit do
    broadcast_prepend_to 'posts', target: 'post_list',  partial: 'posts/post_brc', locals: { post: self, online_user_ids: User.online_users }
  end

online_user_ids, target: - optionaly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment