Class: LcpRuby::ModelFactory::ApiAssociationApplicator

Inherits:
Object
  • Object
show all
Defined in:
lib/lcp_ruby/model_factory/api_association_applicator.rb

Overview

Applies cross-source associations between DB and API models. Runs after all models are registered and data sources attached.

Handles 4 patterns:

  • DB belongs_to API: lazy accessor with instance cache, error → placeholder

  • API belongs_to DB: lazy accessor calling TargetModel.find(fk_value)

  • DB has_many API: lazy accessor calling target data source search

  • API has_many DB: accessor calling TargetModel.where(fk: self.id)

Instance Method Summary collapse

Constructor Details

#initialize(loader) ⇒ ApiAssociationApplicator

Returns a new instance of ApiAssociationApplicator.



12
13
14
# File 'lib/lcp_ruby/model_factory/api_association_applicator.rb', line 12

def initialize(loader)
  @loader = loader
end

Instance Method Details

#apply!Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/lcp_ruby/model_factory/api_association_applicator.rb', line 16

def apply!
  @loader.model_definitions.each_value do |model_def|
    next if model_def.virtual?

    model_class = LcpRuby.registry.model_for(model_def.name)
    next unless model_class

    source_is_api = model_def.api_model?

    model_def.associations.each do |assoc|
      target_def = @loader.model_definitions[assoc.target_model]
      next unless target_def

      target_is_api = target_def.api_model?

      # Only handle cross-source or API-to-API associations
      next if !source_is_api && !target_is_api

      case assoc.type
      when "belongs_to"
        apply_belongs_to(model_class, model_def, assoc, target_def, source_is_api, target_is_api)
      when "has_many"
        apply_has_many(model_class, model_def, assoc, target_def, source_is_api, target_is_api)
      end
    end
  end
end