Class: LiveCable::Observer

Inherits:
Object
  • Object
show all
Defined in:
lib/live_cable/observer.rb

Overview

Observer pattern implementation for tracking changes to reactive variables.

The Observer is attached to delegated values (Arrays, Hashes, ActiveRecord models) and notifies the container when changes occur. This enables automatic re-rendering of components when their data changes.

Architecture:

  • Each Container has one Observer instance
  • Delegators (Array/Hash wrappers) hold references to observers
  • When a mutative method is called on a delegator, it notifies all its observers
  • The observer marks the variable as dirty in the container's changeset
  • After processing a message, the connection broadcasts changes to all dirty components

Examples:

Basic usage

container = Container.new
observer = Observer.new(container)
observer.notify(:username)  # Marks :username as dirty in the container

Instance Method Summary collapse

Constructor Details

#initialize(container) ⇒ Observer

Returns a new instance of Observer.

Parameters:



25
26
27
# File 'lib/live_cable/observer.rb', line 25

def initialize(container)
  @container = WeakRef.new(container)
end

Instance Method Details

#notify(variable) ⇒ void

This method returns an undefined value.

Notify the container that a variable has changed. This marks the variable as "dirty" so the component will be re-rendered.

Examples:

observer.notify(:tags)  # Component will re-render because :tags changed

Parameters:

  • variable (Symbol)

    The name of the reactive variable that changed



37
38
39
40
41
# File 'lib/live_cable/observer.rb', line 37

def notify(variable)
  container.mark_dirty(variable)
rescue WeakRef::RefError
  # Container was already GC'd — nothing to do
end