Class: LiveCable::Delegator
- Inherits:
-
SimpleDelegator
- Object
- SimpleDelegator
- LiveCable::Delegator
- Includes:
- ObserverTracking
- Defined in:
- lib/live_cable/delegator.rb
Overview
Wraps mutable objects (Arrays, Hashes, Models) to track changes.
The Delegator uses Ruby's SimpleDelegator to transparently wrap objects and intercept method calls. When mutative methods are called, observers are notified so the component can be re-rendered.
Architecture:
- Delegator extends SimpleDelegator to wrap the target object
- Dynamically extends with type-specific delegation modules (Array/Hash/Model)
- Each delegation module decorates mutative methods to notify observers
- Getter methods are not decorated (no notification on read)
- Nested structures automatically get wrapped in new Delegators with the same observers
Supported Types:
- Array: Tracks push, <<, delete, etc.
- Hash: Tracks []=, delete, merge!, etc.
- ActiveRecord::Base: Tracks assign_attributes, update, etc.
Class Method Summary collapse
-
.create_if_supported(value, variable, observer) ⇒ Delegator, Object
Factory method to create a Delegator only if the value's type is supported.
-
.supported?(value) ⇒ Boolean
Check if a value's type can be wrapped in a Delegator.
Instance Method Summary collapse
-
#initialize(value) ⇒ Delegator
constructor
A new instance of Delegator.
Methods included from ObserverTracking
#add_live_cable_observer, #initialize_clone, #initialize_dup, #remove_live_cable_observer
Constructor Details
#initialize(value) ⇒ Delegator
Returns a new instance of Delegator.
48 49 50 51 52 53 54 55 56 57 |
# File 'lib/live_cable/delegator.rb', line 48 def initialize(value) super # Extend with the appropriate delegation module based on value's type Delegation::SUPPORTED.each do |klass, delegator| if value.is_a?(klass) extend delegator end end end |
Class Method Details
.create_if_supported(value, variable, observer) ⇒ Delegator, Object
Factory method to create a Delegator only if the value's type is supported. Returns the original value unchanged if not supported.
66 67 68 69 70 71 72 73 74 |
# File 'lib/live_cable/delegator.rb', line 66 def self.create_if_supported(value, variable, observer) if supported?(value) return new(value).tap do |delegator| delegator.add_live_cable_observer(observer, variable) end end value end |
.supported?(value) ⇒ Boolean
Check if a value's type can be wrapped in a Delegator.
80 81 82 |
# File 'lib/live_cable/delegator.rb', line 80 def self.supported?(value) Delegation::SUPPORTED.keys.any? { |c| value.is_a?(c) } end |