Module: Familia::Features::Relationships::ParticipantMethods::Builder

Extended by:
CollectionOperations, Familia::Features::Relationships::Participation::ThroughModelOperations
Defined in:
lib/familia/features/relationships/participation/participant_methods.rb

Overview

Visual Guide for methods added to PARTICIPANT instances:

When Domain calls: participates_in Employee, :domains

Domain instances (PARTICIPANT) get these methods: ├── in_employee_domains?(employee) # Check if I'm in this employee's domains ├── add_to_employee_domains(employee, score) # Add myself to employee's domains ├── remove_from_employee_domains(employee) # Remove myself from employee's domains ├── score_in_employee_domains(employee) # Get my score (sorted_set only) └── position_in_employee_domains(employee) # Get my position (list only)

Note: To update scores, use the DataType API directly: employee.domains.add(domain, new_score, xx: true)

Class Method Summary collapse

Methods included from CollectionOperations

add_to_collection, bulk_add_to_collection, ensure_collection_field, member_of_collection?, remove_from_collection

Methods included from Familia::Features::Relationships::Participation::ThroughModelOperations

build_key, find_and_destroy, find_or_create, validated_attrs

Class Method Details

.build(participant_class, target_class, collection_name, type, as, through = nil, method_prefix = nil) ⇒ Object

Build all participant methods for a participation relationship

Parameters:

  • participant_class (Class)

    The class receiving these methods (e.g., Domain)

  • target_class (Class, String)

    Target class object or 'class' for class-level participation (e.g., Employee or 'class')

  • collection_name (Symbol)

    Name of the collection (e.g., :domains)

  • type (Symbol)

    Collection type (:sorted_set, :set, :list)

  • as (Symbol, nil)

    Optional custom name for relationship methods (e.g., :employees)

  • through (Symbol, Class, nil) (defaults to: nil)

    Through model class for join table pattern



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/familia/features/relationships/participation/participant_methods.rb', line 49

def self.build(participant_class, target_class, collection_name, type, as, through = nil, method_prefix = nil)
  # Determine target name based on participation context:
  # - Instance-level: target_class is a Class object (e.g., Team) → use config_name ("project_team")
  # - Class-level: target_class is the string 'class' (from class_participates_in) → use as-is
  # The string 'class' is passed from TargetMethods.build_class_add_method when calling
  # calculate_participation_score('class', collection_name) for class-level scoring
  target_name = if target_class.is_a?(String)
    target_class  # 'class' for class-level participation
  else
    target_class.config_name  # snake_case class name for instance-level
  end

  # Core participant methods
  build_membership_check(participant_class, target_name, collection_name, type)
  build_add_to_target(participant_class, target_name, collection_name, type, through)
  build_remove_from_target(participant_class, target_name, collection_name, type, through)

  # Type-specific methods
  case type
  when :sorted_set
    build_score_methods(participant_class, target_name, collection_name)
  when :list
    build_position_method(participant_class, target_name, collection_name)
  end

  # Build reverse collection methods on PARTICIPANT class for instance-level participation
  # Skip for class-level participation because:
  # - Class-level uses class_participates_in (e.g., User.all_users)
  # - Bidirectional methods don't make sense: an individual User can't have "all_users"
  # - Class-level collections are accessed directly on the class (User.all_users)
  return if target_class.is_a?(String)  # 'class' indicates class-level participation

  # Priority for method naming:
  # 1. `as:` - most specific, applies to just this collection
  # 2. `method_prefix:` - applies to all collections for this target class
  # 3. Default - uses target_class.config_name
  if as
    # Custom method for just this specific collection
    build_reverse_collection_methods(participant_class, target_class, as, [collection_name])
  elsif method_prefix
    # Custom prefix for all methods related to this target class
    build_reverse_collection_methods(participant_class, target_class, method_prefix, nil)
  else
    # Default pluralized method - will include ALL collections for this target
    build_reverse_collection_methods(participant_class, target_class, nil, nil)
  end
end

.build_add_to_target(participant_class, target_name, collection_name, type, through = nil) ⇒ Object

Build method to add self to target's collection Creates: domain.add_to_customer_domains(customer, score, through_attrs: {})



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/familia/features/relationships/participation/participant_methods.rb', line 200

def self.build_add_to_target(participant_class, target_name, collection_name, type, through = nil)
  method_name = "add_to_#{target_name}_#{collection_name}"

  participant_class.define_method(method_name) do |target_instance, score = nil, through_attrs: {}|
    return unless target_instance&.identifier

    # Use Horreum's DataType accessor instead of manual creation
    collection = target_instance.send(collection_name)

    # Calculate score if needed and not provided
    if type == :sorted_set && score.nil?
      score = calculate_participation_score(target_instance.class, collection_name)
    end

    # Resolve through class if specified
    through_class = through ? Familia.resolve_class(through) : nil

    # Use transaction for atomicity between collection add and reverse index tracking
    # All operations use Horreum's DataType methods (not direct Redis calls)
    target_instance.transaction do |_tx|
      # Add to collection using DataType method (ZADD/SADD/RPUSH)
      ParticipantMethods::Builder.add_to_collection(
        collection,
        self,
        score: score,
        type: type,
        target_class: target_instance.class,
        collection_name: collection_name,
      )

      # Track participation for efficient cleanup using DataType method (SADD)
      track_participation_in(collection.dbkey) if respond_to?(:track_participation_in)
    end

    # TRANSACTION BOUNDARY: Through model operations intentionally happen AFTER
    # the transaction block closes. This is a deliberate design decision because:
    #
    # 1. ThroughModelOperations.find_or_create performs load operations that would
    #    return Redis::Future objects inside a transaction, breaking the flow
    # 2. The core participation (collection add + tracking) is atomic within the tx
    # 3. Through model creation is logically separate - if it fails, the participation
    #    itself succeeded and can be cleaned up or retried independently
    #
    # If Familia's transaction handling changes in the future, revisit this boundary.
    through_model = if through_class
      Participation::ThroughModelOperations.find_or_create(
        through_class: through_class,
        target: target_instance,
        participant: self,
        attrs: through_attrs
      )
    end

    # Return through model if using :through, otherwise self for backward compat
    through_model || self
  end
end

.build_membership_check(participant_class, target_name, collection_name, _type) ⇒ Object

Build method to check membership in target's collection Creates: domain.in_customer_domains?(customer)



186
187
188
189
190
191
192
193
194
195
196
# File 'lib/familia/features/relationships/participation/participant_methods.rb', line 186

def self.build_membership_check(participant_class, target_name, collection_name, _type)
  method_name = "in_#{target_name}_#{collection_name}?"

  participant_class.define_method(method_name) do |target_instance|
    return false unless target_instance&.identifier

    # Use Horreum's DataType accessor instead of manual creation
    collection = target_instance.send(collection_name)
    ParticipantMethods::Builder.member_of_collection?(collection, self)
  end
end

.build_position_method(participant_class, target_name, collection_name) ⇒ Object

Build position method for lists Creates: domain.position_in_customer_domains(customer)



316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/familia/features/relationships/participation/participant_methods.rb', line 316

def self.build_position_method(participant_class, target_name, collection_name)
  method_name = "position_in_#{target_name}_#{collection_name}"

  participant_class.define_method(method_name) do |target_instance|
    return nil unless target_instance&.identifier

    # Use Horreum's DataType accessor instead of manual key construction
    collection = target_instance.send(collection_name)
    # Use DataType method to find position (index in list)
    collection.to_a.index(identifier)
  end
end

.build_remove_from_target(participant_class, target_name, collection_name, type, through = nil) ⇒ Object

Build method to remove self from target's collection Creates: domain.remove_from_customer_domains(customer)



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/familia/features/relationships/participation/participant_methods.rb', line 260

def self.build_remove_from_target(participant_class, target_name, collection_name, type, through = nil)
  method_name = "remove_from_#{target_name}_#{collection_name}"

  participant_class.define_method(method_name) do |target_instance|
    return unless target_instance&.identifier

    # Use Horreum's DataType accessor instead of manual creation
    collection = target_instance.send(collection_name)

    # Resolve through class if specified
    through_class = through ? Familia.resolve_class(through) : nil

    # Use transaction for atomicity between collection remove and reverse index untracking
    # All operations use Horreum's DataType methods (not direct Redis calls)
    target_instance.transaction do |_tx|
      # Remove from collection using DataType method (ZREM/SREM/LREM)
      ParticipantMethods::Builder.remove_from_collection(collection, self, type: type)

      # Remove from participation tracking using DataType method (SREM)
      untrack_participation_in(collection.dbkey) if respond_to?(:untrack_participation_in)
    end

    # TRANSACTION BOUNDARY: Through model destruction intentionally happens AFTER
    # the transaction block. See build_add_to_target for detailed rationale.
    # The core removal is atomic; through model cleanup is a separate operation.
    if through_class
      Participation::ThroughModelOperations.find_and_destroy(
        through_class: through_class,
        target: target_instance,
        participant: self
      )
    end
  end
end

.build_reverse_collection_methods(participant_class, target_class, custom_name = nil, collection_names = nil) ⇒ Object

Generate reverse collection methods on participant class for symmetric access

Creates methods like:

  • user.team_instances (returns Array of Team instances)
  • user.team_ids (returns Array of IDs)
  • user.team? (returns Boolean)
  • user.team_count (returns Integer)

Parameters:

  • participant_class (Class)

    The participant class (e.g., User)

  • target_class (Class)

    The target class (e.g., Team)

  • custom_name (Symbol, nil) (defaults to: nil)

    Custom method name override (base name without suffix)

  • collection_names (Array<Symbol>, nil) (defaults to: nil)

    Specific collections to include (nil = all)



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/familia/features/relationships/participation/participant_methods.rb', line 110

def self.build_reverse_collection_methods(participant_class, target_class, custom_name = nil, collection_names = nil)
  # Determine base method name - either custom or target class config_name
  # e.g., "project_team" or "contracting_org"
  base_name = if custom_name
    custom_name.to_s
  else
    # Use config_name as-is (e.g., "project_team")
    target_class.config_name
  end

  # Store collection names as string array for matching
  collections_filter = collection_names&.map(&:to_s)

  # Generate the main collection method (e.g., user.project_team_instances)
  #
  # Loads actual objects - verifies Redis key existence via load_multi.
  # No caching - load_multi is efficient enough and avoids stale data.
  #
  # @note Error Handling: This method lets database errors bubble up to the
  #   application layer, consistent with Familia's error handling pattern.
  #   Potential failures include:
  #   - Familia::NotConnected - Redis connection unavailable
  #   - Redis::TimeoutError - Operation timed out
  #   - Redis::ConnectionError - Network/connection issues
  #
  #   For production environments, consider wrapping calls in application-level
  #   error handling:
  #
  #   @example Application-level error handling
  #     begin
  #       teams = user.project_team_instances
  #     rescue Familia::PersistenceError => e
  #       # Handle database failure (log, fallback, retry, etc.)
  #       Rails.logger.error("Failed to load teams: #{e.message}")
  #       []  # Return empty array or other fallback
  #     end
  #
  participant_class.define_method("#{base_name}_instances") do
    ids = participating_ids_for_target(target_class, collections_filter)
    # Use load_multi for Horreum objects (stored as Redis hashes)
    target_class.load_multi(ids).compact
  end

  # Generate the IDs-only method (e.g., user.project_team_ids)
  #
  # Shallow - returns IDs from participation index without verifying key existence.
  #
  # @note Database errors (connection, timeout) will bubble up to caller.
  #
  participant_class.define_method("#{base_name}_ids") do
    participating_ids_for_target(target_class, collections_filter)
  end

  # Generate the boolean check method (e.g., user.project_team?)
  #
  # Shallow check - verifies participation index membership, not Redis key existence.
  #
  # @note Database errors (connection, timeout) will bubble up to caller.
  #
  participant_class.define_method("#{base_name}?") do
    participating_in_target?(target_class, collections_filter)
  end

  # Generate the count method (e.g., user.project_team_count)
  #
  # Shallow - counts IDs from participation index without verifying key existence.
  #
  # @note Database errors (connection, timeout) will bubble up to caller.
  #
  participant_class.define_method("#{base_name}_count") do
    participating_ids_for_target(target_class, collections_filter).size
  end
end

.build_score_methods(participant_class, target_name, collection_name) ⇒ Object

Build score-related methods for sorted sets Creates: domain.score_in_customer_domains(customer)

Note: Score updates use DataType API directly: customer.domains.add(domain, new_score, xx: true)



300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/familia/features/relationships/participation/participant_methods.rb', line 300

def self.build_score_methods(participant_class, target_name, collection_name)
  # Get score method
  score_method = "score_in_#{target_name}_#{collection_name}"
  participant_class.define_method(score_method) do |target_instance|
    return nil unless target_instance&.identifier

    # Use Horreum's DataType accessor instead of manual key construction
    collection = target_instance.send(collection_name)
    # Pass self (Familia object) not identifier (string) for correct serialization
    # See GitHub issue #212: serialize_value handles objects vs strings differently
    collection.score(self)
  end
end