top of page

Broadcasting with dependencies in Rails

  • RFilo CTO
  • há 1 minuto
  • 1 min de leitura

Rails makes broadcasting updates easy with broadcast_replace_to, broadcast_append_to, etc. But what if you need to scope the broadcast to the current_user? That’s where dependency injection using Current comes in handy.

Let’s say we want to update a post in real-time only for the current user. You can do that from inside the model like this:


class Post < ApplicationRecord
	after_update_commit -> { broadcast_replace_to [current_user, self] }

	private
	def current_user
		Current.user
	end
end

This tells Rails to create a unique stream for a combination of current_user and the post instance.

On the client side (in your Turbo Streams or views), make sure the stream tag matches this scope:

<%= turbo_stream_from [current_user, post] %>

⚠️ Important: You need to assign Current.user manually — for example, in a controller or job:

class PostsController < ApplicationController
	before_action :set_current_user
	def update
		@post.update(post_params)
	end
	
	private
	def set_current_user
		Current.user = current_user
	end
end

Using Current keeps your models clean and aware of the request context without passing user objects around explicitly.

Clean. Scoped. Real-time. 🚀


 
 
 

Posts recentes

Ver tudo
Captura de tela de 2024-01-01 22-06-25.png

Hi, I'm Rodrigo Toledo

A full-stack developer skilled in both front-end and back-end development, building and maintaining web applications

  • Facebook
  • Youtube
  • LinkedIn
  • Instagram

I don't know everything, help me

Every day, I try to improve what I know about frameworks, and when this occurs, I'll try to share it with the community. Every day, I try to improve my knowledge about frameworks. When this happens, I will try to share it with the community.

Subscribe

Thanks for submitting!

bottom of page