Skip to content

Instantly share code, notes, and snippets.

@MaherSaif
Forked from hopsoft/broadcastable.rb
Created March 29, 2024 18:14
Show Gist options
  • Save MaherSaif/49f6efc8e5200d6a056d1f8c7feb928f to your computer and use it in GitHub Desktop.
Save MaherSaif/49f6efc8e5200d6a056d1f8c7feb928f to your computer and use it in GitHub Desktop.
Broadcastable model concern/mixin
# frozen_string_literal: true
module Broadcastable
extend ActiveSupport::Concern
def prepend_operation(options = {})
operation = {html: ApplicationController.render(partial: to_partial_path, locals: locals)}
operation.merge options
end
def broadcast_prepend(stream, options = {})
cable_ready[stream].prepend(prepend_operation(options)).broadcast
end
def replace_operation(options = {})
operation = {
selector: dom_id(self),
html: ApplicationController.render(partial: to_partial_path, locals: locals)
}
operation.merge options
end
def broadcast_replace(stream, options = {})
cable_ready[stream].replace(replace_operation(options)).broadcast
end
def morph_operation(options = {})
operation = {
selector: dom_id(self),
html: ApplicationController.render(partial: to_partial_path, assigns: {morph: true}, locals: locals)
}
operation.merge options
end
def broadcast_morph(stream, options = {})
cable_ready[stream].morph(morph_operation(options)).broadcast
end
def remove_operation(options = {})
operation = {selector: dom_id(self)}
operation.merge options
end
def broadcast_remove(stream, options = {})
cable_ready[stream].remove(remove_operation(options)).broadcast
end
private
def locals(options = {})
{self.class.table_name.singularize.to_sym => self}.merge(options)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment